Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / JSON

WebApi POST + [ISerializable] + JSON .NET

5.00/5 (3 votes)
6 May 2016CPOL 13.2K  
WebApi POST + [ISerializable] + JSON .NET

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:

C#
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.

C#
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:

C#
[Serializable]
public class ResortModel
{
    public int ResortKey { get; set; }
    public string ResortName { get; set; }
}

Without the [Serializable] attribute, the JSON output is:

JavaScript
{
    "ResortKey": 1,
    "ResortName": "Resort A"
}

With the [Serializable] attribute, the JSON output is:

JavaScript
{
    "<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!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)