Middleware is a component 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.
Middleware class
The custom middleware component is like any other .NET class with Invoke() method. However, in order to execute next middleware in a sequence, it should have RequestDelegate type parameter in the constructor.
The middleware class must include:
- A public constructor with a parameter of type RequestDelegate.
- A public method named Invoke or InvokeAsync. 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).
Visual Studio includes template for creating standard middleware class. For this, right click on the project or folder where you want to create middleware class and select Add -> New Item.
This will open Add New Item popup. Search for word "middleware" in the top right search box as shown below.
Select Middleware Class item and provide a name and click on Add button. This will add a new class for the middleware with extension method as shown below.
As you can see above, the Invoke() method is not asynchronous. So, change it to asynchronous and write your custom logic before calling next();
Add Custom Middleware
Now, we need to add our custom middleware in the request pipeline by using Use extension method as shown below.
We can add middleware using app.UseMiddleware<MyMiddleware>() method of IApplicationBuilder also.
Reference: https://docs.microsoft.com, https://www.tutorialsteacher.com/
0 comments:
Post a Comment