Processing text/plain in ASP.NET Web API
Seems straightforward right? And it is. The only missing piece is that your API doesn’t know what to do when a form body comes across as “Content-Type”: “text/plain”
Have no fear, dotnet core has a class named InputTextFormatter that is a base class for TextInputFormatter which has derived classes for working with JSON and XML. So the below snippets will get you a basic implementation for dealing with plain text and how to add it to your MVC pipeline
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
public class TextPlainFormatter : TextInputFormatter { public TextPlainFormatter() { SupportedMediaTypes.Add("text/plain"); } protected override bool CanReadType(Type type) { return type == typeof(string); } public override async Task<InputFormatterResult> ReadAsync(InputFormatterContext context) { string data = null; using (var streamReader = new StreamReader( context.HttpContext.Request.Body)) { data = await streamReader.ReadToEndAsync(); } return InputFormatterResult.Success(data); } public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding) { throw new NotImplementedException(); } } |
And to make sure that this code is injected in your MVC pipeline. In your Startup.cs or wherever you register your dependencies
1 2 3 4 |
public void ConfigureServices(IServiceCollection services) { services.AddMvc(o => o.InputFormatters.Add(new TextPlainFormatter())); } |
And then inside of your controller
1 2 3 4 5 6 |
[HttpPost] [Route("[controller]")] public async Task<IActionResult> Post([FromBody] string content) { // do something with content } |
And that’s it. You’ve successfully handled text/plain in your controller and can be reused in any other controller action that needs to have text/plain as the content type.






