Web Api - 'ObjectContent类型无法序列化

时间:2014-11-13 22:30:07

标签: c# asp.net-web-api

我有以下Web API操作。

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>

为什么?

更新

我现在有:

  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>

知道为什么吗?

2 个答案:

答案 0 :(得分:2)

您是如何调用API的?看起来它正在尝试使用XML格式化程序进行内容协商。但是,XML序列化程序不支持匿名类型。查看this link了解详细信息。

要解决此问题,您应该发送Accept: application/json标头(如果您使用Fiddler或此类工具),或者明确告诉您的Web API您只需要JSON格式化程序:

config.Formatters.Clear();
var jsonFormatter = new JsonMediaTypeFormatter
{
    // Use camel case formatting.
    SerializerSettings =
    {
        ContractResolver = new CamelCasePropertyNamesContractResolver(),
    }
};
config.Formatters.Add(jsonFormatter);

答案 1 :(得分:0)

我可能错了,但InnerException似乎暗示匿名类型无法序列化。

尝试声明一个类,例如

public class EnumInfo {
    public int Id { get; set; }
    public string Description { get; set; }

    public EnumInfo(int id, string description) {
        Id = id;
        Description = description;
    }
}

将您的Select电话转入

[...].Select(x => new EnumInfo((Int32)x, x.Attribute<DescriptionAttribute>().Description);