Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC Model binding a [Serializable] class

I have this class

[Serializable]
public class MyObject {
    // properties omitted
}

And this WebAPI controller method:

[HttpPost]
[ResponseType(typeof(string))]
public IHttpActionResult SetMyObject(MyObject o) {
    // process object
}

But it fails to model bind to the MyObject class. The object o in the controller method is completely empty, every property is default (so mostly null).

Turns out this is because of the [Serializable] annotation on MyObject. Removing that makes model binding work again.

Is there a way to keep [Serializable] and fix model binding?

like image 622
Christiaan Maks Avatar asked Feb 17 '15 07:02

Christiaan Maks


1 Answers

The answer is in the setting IgnoreSerializableAttribute on the Resolver

((DefaultContractResolver)config.Formatters.JsonFormatter
  .SerializerSettings.ContractResolver)
    .IgnoreSerializableAttribute = true;

Check the:

ASP.NET Web API and [Serializable] class

like image 60
Radim Köhler Avatar answered Sep 27 '22 22:09

Radim Köhler