Record Request Body in ASP.NET Core 3.0–Attempt 2

on Monday, July 13, 2020

In the original post (Record Request Body in ASP.NET Core 3.0), the ITelemetryInitializer was creating some unexpected behavior. It was preventing the Operation ID associated with each request from changing/being updated. So, all the requests that were going through the system were being displayed on the same Performance graph. This created a nearly unusable performance graph as all the request were squished together and unreadable for timing purposes.

So, I needed to remove the ITelemetryInitializer from the code. But, I still wanted to record the JsonBody. The work around I used (which isn’t great) was to create a fake dependency on the request and record the body within the properties of the dependency.

Here’s the code:

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:


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