ASP.NET Core Middleware

Emre Erkoca
2 min readAug 3, 2021

We suppose you want to change requests and responses. You want to add headers to requests, or you want to log your requests and responses. You can use custom middleware. Middleware is assembled into an app pipeline. You can handle requests and responses via middleware.

Photo by Igal Ness on Unsplash

You can see how does middleware work in the app pipeline.

Middleware Pipeline
  1. The request is sending to middleware.
  2. Some operations you want to do. You can change the request here. For example, adding headers to the request.
  3. The request is sending to another middleware.
  4. More logic. So you can do something about the response. For example response logging.

I created two custom middleware for request logging and response logging. You can see a middleware class below. It’s logging each request.

Middleware for request logging

A middleware class must include a public constructor with a parameter of type RequestDelegate and a public method named Invoke or InvokeAsync method with HttpContext parameter.

Middleware for response logging

When you add middleware to Startup.cs Configure method you can use your middleware. It’ll work for each request.

app.UseMiddleware<MiddlewareForRequestLogging>();

app.UseMiddleware<MiddlewareForResponseLogging>();

I won’t explain how to log a request or a response. If you want to learn more about them you can check RecyclableMemoryStream and Stream.

You can also read Microsoft’s document about custom middleware. If you see something wrong you can text me. I don’t want to share wrong information)

You can also read Microsoft’s document about custom middleware. If you see something wrong you can text me. I don’t want to share wrong information)

--

--