5

Trying to find single record using primary key CourseID against odata web.api using this:

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

This is error:

    <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>
Adam Caviness
  • 3,424
  • 33
  • 37
Steve
  • 655
  • 2
  • 9
  • 26
  • 3
    I get this same exception in Web API 2.2 and OData libraries of 6.5.0. This occurs when my action enumerates no results, ie the user queries with a key that doesn't materialize an entity. Your accepted answer regarding QueryableAttribute did not work in the latest bits, any advice? I also ran across [this closed ticket](https://aspnetwebstack.codeplex.com/workitem/1964). – Adam Caviness Aug 12 '14 at 20:57
  • 4
    @AdamCaviness I suffered from the same issue. This link: https://aspnetwebstack.codeplex.com/workitem/1040 seems to suggest that it should actually return a 404 instead of throwing an exception - it doesn't. So I came up with a workaround: https://gist.github.com/andygjp/82106facbb0c43f55dc8. Hope it helps (until they fix it). – andygjp Oct 15 '14 at 22:00

3 Answers3

7

The web.api controller method by default was not queriable, thus client failed. Added annotation to fix: [Queryable(AllowedOrderByProperties = "Id")]

Steve
  • 655
  • 2
  • 9
  • 26
  • 2
    Fixed it for me too, but I would want to understand why!? Why does it have to be queriable in order to be properly serialized? – Dejan Apr 27 '15 at 13:36
1

Try adding the code below to your WebApiConfig.cs file.

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

I think the first two lines are optional if you don't use Json format.

Refer to 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

Feng Zhao
  • 2,977
  • 1
  • 14
  • 20
0

I think you have to make sure any relations are loaded. As a workaround you could create a new DTO (data transfer object) and put all you need in it.

Dunken
  • 8,481
  • 7
  • 54
  • 87