5

尝试使用主键 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>
4

3 回答 3

7

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

于 2014-04-01T12:37:00.730 回答
1

尝试将以下代码添加到您的 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

于 2014-04-01T09:15:15.643 回答
0

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

于 2014-03-31T15:08:02.863 回答