Middleware
is software that's assembled into an app pipeline to handle requests and responses. ASP.NET Core provides a rich set of built-in middleware components, but in some scenarios you might want to write a custom middleware.
Each component:
- Chooses whether to pass the request to the next component in the pipeline.
- Can perform work before and after the next component in the pipeline.
Middleware is generally encapsulated in a class and exposed with an extension method.
The middleware class must include:
- A public constructor with a parameter of type
RequestDelegate
. - A public method named
Invoke
orInvokeAsync
. This method must:- Return a Task.
- Accept a first parameter of type
HttpContext
.
- Additional parameters for the constructor and Invoke/InvokeAsync are populated by dependency injection (DI).
Typically, an extension method is created to expose the middleware through
IApplicationBuilder
.
Language: C#
.Net Version: >=6.0
- Microsoft.AspNetCore.App
- Microsoft.AspNetCore.Http
- Microsoft.AspNetCore.Http.Extensions
- Microsoft.NetCore.App
- Newtonsoft.Json
- .Net SDK
- Visual Studio IDE
- Launch .sln file in
Visual Studio IDE
. - Build the Solution or API project.
- Run the API project.
Swagger UI
will be available at/swagger/index.html
- Select Endpoint, Try it out and Execute.
- Custom formatted response will be displayed under response section.