SingleResult<T> not serializable in Web API when querying by key
Asked Answered
E

3

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>
Eadie answered 31/3, 2014 at 14:41 Comment(2)
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.Aara
@AdamCaviness I suffered from the same issue. This link: 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: gist.github.com/andygjp/82106facbb0c43f55dc8. Hope it helps (until they fix it).Aker
E
7

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

Eadie answered 1/4, 2014 at 12:37 Comment(1)
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?Lozano
G
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

Gonad answered 1/4, 2014 at 9:15 Comment(0)
C
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.

Connection answered 31/3, 2014 at 15:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.