miken.mkndev
miken.mkndev

Reputation: 1951

ASP.NET WebApi 4 Post FromBody Not Binding From JSON

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;
    }
}

Upvotes: 3

Views: 9657

Answers (2)

Sławomir Rosiek
Sławomir Rosiek

Reputation: 4073

I don't know if this is only your formatting, but your current JSON represent array that contains one element of type UserPostData. If that's true change your request to send object instead of array or change your controller to support arrays.

BTW I thing that FromBody is default behavior for complex types like your class.

Upvotes: 1

Kiran
Kiran

Reputation: 57949

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));
        }

Upvotes: 3

Related Questions