I have a WebAPI 2, and I am trying to Post
a model to one of the methods.
My full Postman request looks like this:
POST http://localhost:58900/api/v1/test HTTP/1.1
Host: localhost:58900
Connection: keep-alive
Content-Length: 295
Authorization: Bearer <<my bearer token>>
Postman-Token: 970cb0c1-3a8c-7a1e-763a-7dd916c035f3
Cache-Control: no-cache
Origin: chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36
Content-Type: application/json
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,sv;q=0.6,fr;q=0.4
{
MyProperty: 'Test',
MyGuid: '67345ac2-551e-d16e-b448-e697e369dea1'
}
My controller method looks like this:
[HttpPost]
public IHttpActionResult Post([FromBody]MyModel myModel)
{
//Doing stuff
}
Everything works as expected but when I add the Serializable
attribute to my model all values become null, as such:
[Serializable]
public class MyModel
{
public string MyProperty { get; set; }
public Guid MyGuid { get; set; }
}
[HttpPost]
public IHttpActionResult Post([FromBody]MyModel myModel)
{
//myModel.MyProperty is null and myModel.MyGuid is {00000000-0000-0000-0000-000000000000}
}
I assume(?) that this is because the Serialization
attribute is telling the runtime to use a binary formatter instead of the JsonFormatter
specified in my configuration - but then, what is the best way to work around this?
The reason I need the Serialization
attribute in the first place is to allow deep copy
of the objects;
public static List<T> Clone<T>(this IEnumerable<T> list)
{
var ms = new MemoryStream();
var bf = new BinaryFormatter();
bf.Serialize(ms, list);
ms.Position = 0;
return bf.Deserialize(ms) as List<T>;
}