Correctly Posting String Data To A WebAPI Controller

22 July 2015

Seems like a pretty simple scenario, right? So I got to work and wrote the following:

[HttpPost]
[Route("api/users/me/delete")]
public HttpResponseMessage CoolMethod(string myData)
{
}

However, when attempting to actually call into the controller, all I was getting back was 404/not found errors. Seems strange, right? The following worked without issue, though:

[HttpPost]
[Route("api/users/me/delete")]
public HttpResponseMessage CoolMethod()
{
}

So I could get to the method at that URL, provided it didn't have a string parameter.

A bit of research Google later, it turns out that this behaviour is due to how parameter binding works in ASP.NET Web API. By default (whether you like it or not), all simple types including strings are assumed to be provided as part of the URI, regardless of the endpoint's verb (GET/POST).

Luckily, there's a very easy fix - you just need to tell it that you're expecting the parameter to come from the body of the post instead with the [FromBody] parameter, like follows:

[HttpPost]
[Route("api/users/me/delete")]
public HttpResponseMessage CoolMethod([FromBody] string myData)
{
}

As a sidenote, to do the reverse (ie provide complex objects via the URI), you can use the [FromUri] attribute.

Tags: MVC, WebAPI

Add a Comment

No Comments