【问题标题】:SingleResult<T> not serializable in Web API when querying by key按键查询时,SingleResult<T> 在 Web API 中不可序列化
【发布时间】:2014-05-10 23:16:52
【问题描述】:

尝试使用主键 CourseID 针对 odata web.api 查找单个记录:

var editedcourse = container.Courses.Where(c => c.CourseID == ID).SingleOrDefault();

这是错误:

    <m:innererror>
    <m:message>The 'ObjectContent`1' type failed to serialize the response body for content type 'application/atom+xml; charset=utf-8'.</m:message>
    <m:type>System.InvalidOperationException</m:type>
    <m:stacktrace></m:stacktrace>
    <m:internalexception>
      <m:message>'SingleResult`1' cannot be serialized using the ODataMediaTypeFormatter.</m:message>
      <m:type>System.Runtime.Serialization.SerializationException</m:type>

【问题讨论】:

  • 我在 Web API 2.2 和 6.5.0 的 OData 库中遇到了同样的异常。当我的操作未枚举任何结果时会发生这种情况,即用户使用未实现实体的键进行查询。您接受的关于 QueryableAttribute 的答案在最新版本中不起作用,有什么建议吗?我也遇到过this closed ticket
  • @AdamCaviness 我遇到了同样的问题。此链接:aspnetwebstack.codeplex.com/workitem/1040 似乎暗示它实际上应该返回 404 而不是抛出异常 - 它没有。所以我想出了一个解决方法:gist.github.com/andygjp/82106facbb0c43f55dc8。希望它有所帮助(直到他们修复它)。

标签: odata wcf-data-services asp.net-web-api asp.net-web-api-odata


【解决方案1】:

web.api 控制器方法默认不可查询,因此客户端失败。添加注释修复:[Queryable(AllowedOrderByProperties = "Id")]

【讨论】:

  • 也为我修复了它,但我想知道为什么!?为什么它必须是可查询的才能被正确序列化?
【解决方案2】:

尝试将以下代码添加到您的 WebApiConfig.cs 文件中。

var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);

如果你不使用 Json 格式,我认为前两行是可选的。

参考 http://social.msdn.microsoft.com/Forums/vstudio/en-US/a5adf07b-e622-4a12-872d-40c753417645/web-api-error-the-objectcontent1-type-failed-to-serialize-the-response-body-for-content?forum=wcf

【讨论】:

    【解决方案3】:

    我认为您必须确保已加载任何关系。作为一种解决方法,您可以创建一个新的 DTO(数据传输对象)并将您需要的所有内容放入其中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-27
      • 1970-01-01
      • 1970-01-01
      • 2013-04-27
      • 1970-01-01
      • 2021-04-28
      • 1970-01-01
      相关资源
      最近更新 更多