I have an ASP.NET Web API endpoint with controller action defined as follows :
[HttpPost]
public HttpResponseMessage Post([FromBody] object text)
If my post request body contains plain text ( i.e. should not be interpreted as json, xml, or any other special format ), then I thought I could just include following header to my request :
Content-Type: text/plain
However, I receive error :
No MediaTypeFormatter is available to read an object of type 'Object' from content with media type 'text/plain'.
If I change my controller action method signature to :
[HttpPost]
public HttpResponseMessage Post([FromBody] string text)
I get a slightly different error message :
No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'.
Actually it's a shame that web API doesn't have a
MediaTypeFormatter
for plain text. Here is the one I implemented. It can also be used to Post content.You need to "register" this formatter in your HttpConfig by something like that:
In some situations it might be simpler to let the JsonMediaTypeFormatter let do the work:
In ASP.NET Core 2.0 you simply do the following :-
Since Web API doesn't have out of box formatter for handling text/plain, some options:
Modify your action to have no parameters... reason is having parameters triggers request body de-serialization. Now you can read the request content explicitly by doing
await Request.Content.ReadAsStringAsync()
to get the stringWrite a custom MediaTypeFormatter to handle 'text/plain'... it's actually simple to write in this case and you could keep the parameters on the action.
Purified version using of gwenzek's formatter employing async/await:
Please note I intentionally do not dispose StreamReader/StreamWriter, as this will dispose underlying streams and break Web Api flow.
To make use of it, register while building HttpConfiguration: