c# - Web Api - The 'ObjectContent type failed to serialize -
i have next web api action.
public ihttpactionresult get() { var units = enum.getvalues(typeof(unittype)).cast<unittype>().select(x => new { id = (int32)x, description = x.attribute<descriptionattribute>().description }); homecoming ok(units); }
basically, returning values , descriptions of enum.
i checked units list , right values.
however, when phone call api next error:
<error><message>an error has occurred.</message> <exceptionmessage>the 'objectcontent`1' type failed serialize response body content type 'application/xml; charset=utf-8'.</exceptionmessage> <exceptiontype>system.invalidoperationexception</exceptiontype> <stacktrace/><innerexception><message>an error has occurred.</message> <exceptionmessage>type '<>f__anonymoustype0`2[system.int32,system.string]' cannot serialized. consider marking datacontractattribute attribute, , marking of members want serialized datamemberattribute attribute. if type collection, consider marking collectiondatacontractattribute. see microsoft .net framework documentation other supported types.</exceptionmessage>
why?
update
i have:
public ihttpactionresult get() { ilist<enummodel> units = enum.getvalues(typeof(unittype)).cast<unittype>().select(x => new enummodel((int32)x, x.attribute<descriptionattribute>().description)).tolist(); homecoming ok(units); } // public class enummodel { public int32 id { get; set; } public string description { get; set; } public enummodel(int32 id, string description) { id = id; description = description; } // enummodel } // enummodel
i error:
<error> <message>an error has occurred.</message> <exceptionmessage>the 'objectcontent`1' type failed serialize response body content type 'application/xml; charset=utf-8'.</exceptionmessage> <exceptiontype>system.invalidoperationexception</exceptiontype> <stacktrace/><innerexception> <message>an error has occurred.</message> <exceptionmessage>type 'helpers.enummodel' cannot serialized. consider marking datacontractattribute attribute, , marking of members want serialized datamemberattribute attribute. if type collection, consider marking collectiondatacontractattribute. see microsoft .net framework documentation other supported types.</exceptionmessage> <exceptiontype>system.runtime.serialization.invaliddatacontractexception</exceptiontype>
any thought why?
i might wrong, innerexception
seems suggesting anonymous types can't serialized.
try declaring class such as
public class enuminfo { public int id { get; set; } public string description { get; set; } public enuminfo(int id, string description) { id = id; description = description; } }
and turning select
phone call
[...].select(x => new enuminfo((int32)x, x.attribute<descriptionattribute>().description);
c# asp.net-web-api
No comments:
Post a Comment