API Request and Response Logging Middleware using .NET 5 (C#)

Alex Bierhaus
3 min readMar 8, 2021

In an API-First world, you as a developer might challenge log requests and responses of your application. While this would have been a code-heavy task years ago to implement logging for each API method, the build in .NET logging and middleware infrastructure can help you achieve this task.

In this article, I will show you how to log each request and response in your application.

You can find a complete working example here on GitHub.

What is middleware?

Middleware is an old IT concept that “sits” on top of several applications to handle requests and responses. Middleware is used when you have to handle situations that occur for every request/ response and should not be handled on the core backend site. .NET allows us to have multiples middlewares pieced together, which allows you as a developer to “plugin” your custom middleware.

Our Request and Response logging is the perfect example for middleware use since it occurs in each request and response.

Setup

Just create a new ASP.NET Core Web API or ASP.NET Core Web project that targets the .NET 5 framework. The example will also work with .NET Core 3.x

Creating the middleware

Create a new class called “HttpLoggingMiddleware” and copy over the following code

The constructor of the middleware takes the RequestDelegate delegate as a default parameter. Besides, we use the default logging component for logging the requests and responses. Whenever a Request occurs, the Invoke method is called. In our case, this method gets the response object, parses the required content, and logs its value. The current response is stored as a copy since streams can only be read once. Afterward, it calls the next middleware pipeline in the chain. After completing each middleware, the new response is taked, formatted again, and the value is once more saved.

Final steps

Your middleware has to be configured in your Startup.cs.

Besides, you have to configure your logging provider. We use the basic console logging here:

Now you can run the application, call your web methods, and will see the output in the console:

Summary

In this article, we created a simple but powerful middleware that logs requests and responses that will work out-of-the-box in your application. Furthermore, it gives you a basic understanding of what you can further do with middleware in .NET.

--

--

Alex Bierhaus

Entrepreneur — technologist — passionate leader