Json – ASP.NET WebApi 4 Post FromBody Not Binding From JSON

asp.net-web-apijson

I have a simple question. I am building an HTTP REST service in ASP.NET WebApi 4 and I am having some trouble getting my model bindings to work.

I am using the following code to accept a POST HTTP request and process a login. From what I can gather ASP.NET WebApi 4 will deserialize the JSON for you and bind to the accepted model. I have setup my model, but whenever I test the service via the debugger I get an NullReferenceExecption on the UserPostData object.

From what I can tell I have everything setup correct, but it's just not working. Below is my JSON that I am posting. Does anyone have any idea why I am getting this error?

JSON
[
{
"Username": "mneill",
"Password": "12345"
}
]

Code From WebApi 4 Controller Class

public class UserPostData
{
    public string Username { get; set; }
    public string Password { get; set; }
}

public class UserController : ApiController
{
    //
    // GET: /User/

    public string[] Get(string username)
    {
        return new string[]
        {
            "username",
            username
        };
    }

    public HttpResponseMessage Post([FromBody] UserPostData body)
    {
        //string username = postData.Username;
        //string password = postData.Password;

        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);

        if (body.Username == null)
            response.StatusCode = HttpStatusCode.NotFound;
        if (body.Password == null)
            response.StatusCode = HttpStatusCode.NotFound;

        return response;
    }
}

Best Solution

Make sure that the Content-Type header is present in your request.

Modify your Json to be like below:

{ "Username": "mneill", "Password": "12345" }

And also add the following code in your Post action to see any model binding errors:

if (!ModelState.IsValid)
        {
            throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, this.ModelState));
        }