Post JSON string to WEB API
I edited your code and it works well.
A [FromBody] attribute specifies that an action parameter comes only from the entity body of the incoming HTTPRequestMessage.
public class TestApiController : ApiController
{
// POST api/<controller>
[HttpPost]
public HttpResponseMessage Post([FromBody]string value)
{
return new HttpResponseMessage()
{
Content = new StringContent("POST: Test message: " + value)
};
}
}
function sendRequest() {
var Test = { "Name": "some name" };
$.ajax({
type: "POST",
url: "api/TestApi",
data: { '': JSON.stringify(Test) }
}).done(function (data) {
alert(data);
}).error(function (jqXHR, textStatus, errorThrown) {
alert(jqXHR.responseText || textStatus);
});
}
Either treat the POST request as a generic HTTP request, and manually parse the body:
public async Task<HttpResponseMessage> Post(HttpRequestMessage request)
{
var jsonString = await request.Content.ReadAsStringAsync();
// deserialize the string, or do other stuff
return new HttpResponseMessage(HttpStatusCode.OK);
}
Or use a generic JToken, and let the serializer do the rest:
public HttpResponseMessage Post([FromBody] JToken model)
{
DoStuff(model);
var myField = model["fieldName"];
return new HttpResponseMessage(HttpStatusCode.OK);
}
Notes: this way you do not need to alter client-side code, because you are still POSTing json data, not a generic string, which is semantically the right choice if you expect your client to post serialized JSON objects.
References:
http://bizcoder.com/posting-raw-json-to-web-api