Grant
Grant

Reputation: 73

ContentType application/json in ASP.NET WebAPI

I'm building my first WebAPI using ASP.NET MVC 4 WebAPI.

The requests must be sent using the application/json ContentType with utf-8 as the character set.

My POST method looks like this:

    public HttpResponseMessage Post([FromBody]string value)
    {
        return new HttpResponseMessage(HttpStatusCode.OK);
    }

Whenever I'm sending a POST request the parameter 'value' is null. The request body contains Json: { "name":"test" }.

What I prefer is to have the parameter of the Post method to be either a string containing the Json or be of type JObject (from the JSON.NET library). How do I accomplish this? And is this even possible?

Upvotes: 3

Views: 5327

Answers (1)

tpeczek
tpeczek

Reputation: 24125

The easiest way is to grab the raw string directly from Request.Content:

public async Task<HttpResponseMessage> Post()
{
    string value = await Request.Content.ReadAsStringAsync();

    return new HttpResponseMessage(HttpStatusCode.OK);
}

There is a way to make ASP.NET Web Api treat your request body as string content, but in order to do that the content must be in =value format, in your case something like this:

={ "name":"test" }

You can achieve something like this with following jQuery code (for example):

$.post('api/values', '=' + JSON.stringify({ name: 'test' }));

In that case you can use signature from your question.

In the end there is always an option of creating your own MediaTypeFormatter to replace the default JsonMediaTypeFormatter and make it always deserialize the content into JObject. You can read more about creating and registering MediaTypeFormatter here and here.

Upvotes: 2

Related Questions