I'm not entirely sure whats happened here. I may have messed things up somewhere, but I don't know what.
My API controller method looks like this:
public HttpResponseMessage<string> Put(int id)
I've tried a string as well with the same error.
Any ideas?
Thanks.
Edit: To be clear - the id is the route parameter. The body of the request is JSON. If I remove the route parameter,the method functions as normal.
Surprisingly, int and string do not have a MediaTypeFormatter by default, so it doesn't know how to handle those types.
The only types it knows how to handle out of the box are JSON, XML, and form url-encoded data. This quote is from the official asp.net website, http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters
In Web API, the media type determines how Web API serializes and deserializes the HTTP message body. There is built-in support for XML, JSON, and form-urlencoded data, and you can support additional media types by writing a media formatter.
Now you 'can' write your own MediaTypeFormatter (the link I provided will show you how), but since the asp.net web api is still in beta I have had a lot of trouble with it using custom formatters for simple types like strings. I found it is much easier just to wrap whatever value you would like to PUT in xml / json and it will automatically get deserialized. See my post here for more info on that, When HTTP-POST has body, url parameter is null
For your specific example your PUT body would look like,
<message>
<id>6</id>
</message>
Then be sure to set the content-type of your http request to text/xml (or application/json if you choose to use that). And it should serialize just fine into the variable.
Are you placing the int value in the body of the request message? If so, what is the format?
If the content type is text, Web API won't know what to do with it, because Web API does not provide a media formatter for text. You can write a custom formatter, as Despertar noted.
You can also do something like this:
public void Put()
{
var s = Request.Content.ReadAsStringAsync().Result;
}
Please read following blog post:
This describes most typical issues with using simple parameters. Without knowing any more details about how your request looks it is not possible to determine which one you have hit.
UPDATE
There is one more known bug considering route values. In case when not one of built in formatters is used for POST/PUT/PATCH request, the route values parameters are not being bind. To work around this the best solution is to write ActionFilterAttribute as described below:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With