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

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?

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

Setup

Creating the middleware

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

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

Entrepreneur — technologist — passionate leader