Accepting Raw Request Body Content with ASP.NET Core 2 Web API

Rick Strahl wrote an excellent article on Accepting Raw Request Body Content with ASP.NET Web API.

Although ASP.NET Core 2 have excellent support to receive xml content but I wanted to receive raw xml in endpoint i.e. Accept Raw Request Body Content with ASP.NET Web API but for .Net Core 2. I knew of Rick’s article so naturally I tried to just convert the solution to .Net Core 2 originally with no success as obviously some base classes are missing in .Net Core 2 to port the solution.

Google pointed me to Custom Formatters in ASP.NET Core MVC Web APIs and I also came across Building Custom Formatters for .Net Core article from Fiyaz Hasan that put me to right direction. So let’s dive in to the code.

Create ASP.NET Core Web API Project

Create an ASP.NET Core Web API project with Visual Studio, it can be ASP.NET Core Web App project as well but I have chosen Web API template for simplicity and also named it RawRequestBodySample.

Add Custom Input Formatter

  • Add a new folder named Formatters to project
  • Add a new class RawRequestBodyInputFormatter in the folder
  • Inherit this new class from InputFormatter (namespace Microsoft.AspNetCore.Mvc.Formatters)
  • Override CanRead, for simplicity I am always returning true
public override Boolean CanRead(InputFormatterContext context)
{
return true;
}
  • Override ReadRequestBodyAsync, for this sample I am reading all content as string but you can change it to byte[] or anything else you need also I have removed failure path for brevity.
public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
var request = context.HttpContext.Request;
using (var reader = new StreamReader(request.Body))
{
var content = await reader.ReadToEndAsync();
return await InputFormatterResult.SuccessAsync(content);
}
}

Add Controller and EndPoint

  • Remove default ValuesController added by project template
  • Add new controller RawRequestBodyController
  • Implement Post method with following signature
public async Task<ContentResult> Post([FromBody] string body)
  • Process raw request, for this sample I am just returning the request with StatusCode 200.

Configure Services

Configure our custom input formatter to be used by Mvc. Add the following code in ConfigureServices in Startup.cs.

services.AddMvc(options =>
{
options.InputFormatters.Insert(0, new RawRequestBodyInputFormatter());
});

Testing time…

Finally testing time.

Code

Sample code for this article can is available on GitHub.

References