繁体   English   中英

使用ApiController获取列表时出现System.InvalidOperationException

[英]System.InvalidOperationException when getting a List with an ApiController

当我在应用程序中访问/WeedAPI/ URL时,出现以下错误。 如何使我的Web API正常工作? (控制器,遵循的模型代码)

完整的错误详细信息:

<Error>
    <Message>An error has occurred.</Message>
    <ExceptionMessage>
        The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.
    </ExceptionMessage>
    <ExceptionType>System.InvalidOperationException</ExceptionType>
    <StackTrace/>
    <InnerException>
        <Message>An error has occurred.</Message>
        <ExceptionMessage>
            Type 'WeedCards.Models.Weed' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute. See the Microsoft .NET Framework documentation for other supported types.
        </ExceptionMessage>
        <ExceptionType>
            System.Runtime.Serialization.InvalidDataContractException
        </ExceptionType>
        <StackTrace>
            at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.ThrowInvalidDataContractException(String message, Type type) at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.CreateDataContract(Int32 id, RuntimeTypeHandle typeHandle, Type type) at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.GetDataContractSkipValidation(Int32 id, RuntimeTypeHandle typeHandle, Type type) at System.Runtime.Serialization.XmlObjectSerializerContext.GetDataContract(Int32 id, RuntimeTypeHandle typeHandle) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle) at WriteArrayOfWeedToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , CollectionDataContract ) at System.Runtime.Serialization.CollectionDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeAndVerifyType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, Boolean verifyKnownType, RuntimeTypeHandle declaredTypeHandle, Type declaredType) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType) at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.DataContractSerializer.WriteObject(XmlWriter writer, Object graph) at System.Net.Http.Formatting.XmlMediaTypeFormatter.<>c__DisplayClass7.<WriteToStreamAsync>b__6() at System.Threading.Tasks.TaskHelpers.RunSynchronously(Action action, CancellationToken token)
        </StackTrace>
    </InnerException>
</Error>

我的ApiController子类:

public class WeedAPIController : ApiController
{
    //
    // GET: /WeedAPI/

    public IEnumerable<Weed> GetAllWeeds()
    {
        return WeedData.GetWeeds();
    }

}

我的资料:

public class WeedData
{
    public static Dictionary<string,WeedFamily> GetFamilies(){
        return new Dictionary<string,WeedFamily>
        {
             {"mustard",new WeedFamily("Mustard","Brassicaceae")}
            ,{"pigweed",new WeedFamily("Pigweed","Amaranthus")}
            ,{"sunflower",new WeedFamily("Sunflower","Asteraceae")}
        };
    }

    public static List<Weed> GetWeeds(){
        var Families = GetFamilies();
        return new List<Weed>
        {
             new Weed("Hairy Bittercress","Cardamine hirsuta",Families["mustard"])
            ,new Weed("Little Bittercress","Cardamine oligosperma",Families["mustard"])
            ,new Weed("Shepherd's-Purse","Capsella bursa-pastoris",Families["mustard"])
            ,new Weed("Wild Mustard","Sinapis arvensis / Brassica kaber",Families["mustard"])
            ,new Weed("Wild Radish","Raphanus raphanistrum",Families["mustard"])
            ,new Weed("Radish","Raphanus sativus",Families["mustard"])
            ,new Weed("Redroot Pigweed","Amaranthus retroflexus",Families["pigweed"])
            ,new Weed("Prickly Lettuce","Lactuca serriola",Families["sunflower"])
            ,new Weed("Spiny Sowthistle","Sonchus asper",Families["sunflower"])
            ,new Weed("Annual Sowthistle","Sonchus oleraceus",Families["sunflower"])

        };
    }
}

答案是例外。 [DataContract]标记Weed类,以便可以由DataContractSerializer对其进行序列化。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM