Question

I have the following code:

[HttpPost]
public async Task<ReturnStatus> Delete([FromBody]int id)
{
    await new BusinessLogic.Templates().DeleteTemplate(id);

    return ReturnStatus.ReturnStatusSuccess();
}

When I run this as an AJAX request, the id is null. I've inspected the data coming in through Fiddler and the body is:

{"id":"11"}

The header has Content-Type: application/json; charset=UTF-8.

If I modify the code slightly to

[HttpPost]
public async Task<ReturnStatus> Delete([FromBody]string id)
{
    await new BusinessLogic.Templates().DeleteTemplate(Convert.ToInt64(id));

    return ReturnStatus.ReturnStatusSuccess();
}

it works just fine.

What am I doing wrong here?

Était-ce utile?

La solution

Please read this part, number 3 in particular: http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/ 3. [FromBody] parameters must be encoded as =value (quoting the section for future reference:)

There are two ways to make jQuery satisfy Web API’s encoding requirement. First, you can hard code the = in front of your value, like this:

$.post('api/values', "=" + value);

Personally, I’m not a fan of that approach. Aside from just plain looking kludgy, playing fast and loose with JavaScript’s type coercsion is a good way to find yourself debugging a “wat” situation. Instead, you can take advantage of how jQuery encodes object parameters to $.ajax, by using this syntax:

$.post('api/values', { '': value });
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top