I have an ASP.NET Web API endpoint with controller action defined as follows :
[HttpPost]
public HttpResponseMessage Post([FromBody] object text)
Purified version using of gwenzek's formatter employing async/await:
public class PlainTextFormatter : MediaTypeFormatter
{
public PlainTextFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
}
public override bool CanReadType(Type type) =>
type == typeof(string);
public override bool CanWriteType(Type type) =>
type == typeof(string);
public override async Task
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:
protected HttpConfiguration CreateHttpConfiguration()
{
HttpConfiguration httpConfiguration = new HttpConfiguration();
...
httpConfiguration.Formatters.Add(new PlainTextFormatter());
...
return httpConfiguration;
}