frenchie
frenchie

Reputation: 52027

WebAPI POST request parameters are null

I'm trying to do a POST request of a json object and convert it into a class but it's not working. Here's the JS that's sending the object:

var TheAjaxData = {
    'Property1': 'TheValue1',
    'Property2': 'TheValue2',
    'Property3': 'TheValue3'
}

$.ajax({
    url: "/thewebapi/themethod",
    type: "POST",
    data: TheAjaxData,
    contentType: 'application/json; charset=utf-8',
    success: function (msg, textStatus, request) {
        console.log(msg);
    }
});

The WebAPI receives the request so I know the routing is correct but TheObject is null. This is the code:

[RoutePrefix("thewebapi")]
public class TheWebAPIController : ApiController
{
    [Route("themethod")]
    public HttpResponseMessage Post([FromBody] TheRequestObjectModel TheObject)
    {
        var testvalue = TheObject.Property1;
    }

    public class TheRequestObjectModel
    {
        public string Property1 { get; set; }
        public string Property2 { get; set; }
        public string Property3 { get; set; }
    }
}

This needs to work with a POST, not a GET. I'm pretty sure I'm close but it's not working. What do I need to change to get the object I'm sending converted into TheRequestObjectModel?

Upvotes: 2

Views: 102

Answers (2)

Ajay Kumar Oad
Ajay Kumar Oad

Reputation: 560

Try to convert your js object into json (as json formats your data in an object):

var TheAjaxData = {
    'Property1': 'TheValue1',
    'Property2': 'TheValue2',
    'Property3': 'TheValue3'
}

$.ajax({
    url: "/thewebapi/themethod",
    type: "POST",
    data: JSON.stringify(TheAjaxData),
    contentType: 'application/json; charset=utf-8',
    success: function (msg, textStatus, request) {
        console.log(msg);
    }
});

Upvotes: 2

Emre Kabaoglu
Emre Kabaoglu

Reputation: 13146

If you want to decorate the API action with [FromBody], you should serialize to Json when posting the data from client side. You can use JSON.stringify(TheAjaxData).

$.ajax({
    url: "/thewebapi/themethod",
    type: "POST",
    data: JSON.stringify(TheAjaxData),
    contentType: 'application/json; charset=utf-8',
    success: function (msg, textStatus, request) {
        console.log(msg);
    }
});

Another option is removing the [FromBody] attribute and pass the javascript object directly. Actually, in your case TheRequestObjectModel just have string properties and it doesn't contain another complex object. So, It could be better to remove the [FromBody] attribute.

[Route("themethod")]
public HttpResponseMessage Post(TheRequestObjectModel TheObject)
{
    var testvalue = TheObject.Property1;
}

$.ajax({
    url: "/thewebapi/themethod",
    type: "POST",
    data: TheAjaxData,
    contentType: 'application/json; charset=utf-8',
    success: function (msg, textStatus, request) {
        console.log(msg);
    }
});

Upvotes: 1

Related Questions