Record Request Body in ASP.NET Core 3.0

on Monday, June 15, 2020

Application Insights is a great tool, but it doesn’t record the body of a request by default. This is for good reason, payloads can be large and can sometimes contain sensitive information. But … sometimes you just need to record them.

When you do a google search there’s a great StackOverflow post (View POST request body in Application Insights) which gives you a lot of hope that it can be setup easily. But, with all the advancements in ASP.NET Core 3.0, it’s not quiet as easy as that post makes it look.

Here’s the obstacles you may need to overcome:

  • In ASP.NET Core 3.0, the request’s Body is no longer available to be read after a particular point in the application pipeline. You will need to create a middleware component to “EnableBuffering”. (This was done for purposes of speed as the underlying layers of the stack were replaced with Span’s. There’s a new Request.BodyReader that works with the spans for high performance, but it’s also not available to be read after a particular point in the application pipeline.)
  • The ITelemetryInitializer runs after a request completes. This means that the request’s body is disposed of by the time the initializer runs and records the event. You will have to record the body somewhere after “EnableBuffering” is enabled and before the Action completes. Like inside of an IActionFilter.
  • You may not want to record the body of everything that flows through your website, so an ActionFilterAttribute can make it easy to select which action you would like to record.

So, here’s some code that can help accomplish that:

0 comments:

Post a Comment


Creative Commons License
This site uses Alex Gorbatchev's SyntaxHighlighter, and hosted by herdingcode.com's Jon Galloway.