At work, I have taken on the task of building a small utility web site for admin needs. The thing is I wanted it to be very self contained so I have opted for this:
- Self hosted web API
- JSON data exchanges
Aurelia.IO
front end - Raven DB database
So I set out to create a nice web API endpoint like this:
private IDocumentStore _store;
public LoginController(IDocumentStore store)
{
_store = store;
}
[HttpPost]
public IHttpActionResult Post(LoginUser loginUser)
{
}
Where I then had this datamodel that I was trying to post via the awesome AWEWSOME REST plugin for Chrome.
using System;
namespace Model
{
[Serializable]
public class LoginUser
{
public LoginUser()
{
}
public LoginUser(string userName, string password)
{
UserName = userName;
Password = password;
}
public string UserName { get; set; }
public string Password { get; set; }
public override string ToString()
{
returnstring.Format("UserName: {0}, Password: {1}", UserName, Password);
}
}
}
This just would not work, I could see the endpoint being called ok, but no matter what I did, the LoginUser
model only the post would always have NULL
properties. After a little fiddling, I removed the [Serializable]
attribute and it all just started to work.
Turns out this is to do with the way JSON.NET works when it sees the [Serializable]
attribute.
For example, if you had this model:
[Serializable]
public class ResortModel
{
public int ResortKey { get; set; }
public string ResortName { get; set; }
}
Without the [Serializable]
attribute, the JSON output is:
{
"ResortKey": 1,
"ResortName": "Resort A"
}
With the [Serializable]
attribute, the JSON output is:
{
"<ResortKey>k__BackingField": 1,
"<ResortName>k__BackingField": "Resort A"
}
I told one of my colleagues about this, and he found this article: http://stackoverflow.com/questions/29962044/using-serializable-attribute-on-model-in-webapi which explains it all nicely including how to fix it.
Hope that helps!