I have an ASP.NET WEB-API 2
app witch needs to have a POST
method that accepts a JOSN
string
with unknown structure from javascript
.
I enabled cors
and GET
methods works fine, however when sending JSON
from the client the api's method parameter is always null
.
This is my api
method:
//parameters i tried:
//[FromBody]string model
//[FromBody]dynamic model
//dynamic model
public HttpResponseMessage Post(string model)
{
return new HttpResponseMessage()
{
Content = new StringContent("POST: Test message: " + model)
};
}
and my client method:
function sendRequest()
{
var Test = {"Name":"some name"};
var method = $('#method').val();
$.ajax({
type: method,
url: serviceUrl,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(Test)
}).done(function (data)
{
$('#value1').text(data);
}).error(function (jqXHR, textStatus, errorThrown)
{
$('#value1').text(jqXHR.responseText || textStatus);
});
}
So the question is how can I post an unknown JSON string
from javascript
and accept it as a string in my api
method?
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.
Either treat the POST request as a generic HTTP request, and manually parse the body:
Or use a generic JToken, and let the serializer do the rest:
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