我有以下Web API操作。Web Api - 'ObjectContent類型未能序列化
public IHttpActionResult Get() {
var units = Enum.GetValues(typeof(UnitType)).Cast<UnitType>().Select(x => new { Id = (Int32)x, Description = x.Attribute<DescriptionAttribute>().Description });
return Ok(units);
}
基本上,我返回一個枚舉的值和說明。
我檢查了單位列表,我得到了正確的值。
然而,當我打電話,我得到以下錯誤的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 '<>f__AnonymousType0`2[System.Int32,System.String]' 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>
爲什麼?
UPDATE
我現在有:
public IHttpActionResult Get() {
IList<EnumModel> units = Enum.GetValues(typeof(UnitType)).Cast<UnitType>().Select(x => new EnumModel((Int32)x, x.Attribute<DescriptionAttribute>().Description)).ToList();
return Ok(units);
} // Get
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
我得到的錯誤:
<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 'Helpers.EnumModel' 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>
任何想法,爲什麼?
我試着用班級,因爲你建議,但我一直有相同的錯誤... –
@MDMoura你可以請編輯你的問題,包括你得到的錯誤*現在*? –
我剛更新了我的問題......我的課似乎很正常,所以我不知道爲什麼我現在得到這個錯誤。 –