Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the middleware of ASP.NETCore

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

In this issue, the editor will bring you middleware about how to use ASP.NETCore. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

Preface

We know that any web framework encapsulates a http request into a pipeline, and each request is a series of operations through the pipeline, and finally reaches the code we write. Then middleware is a component in the application pipeline that is used to intercept the request process for some other processing and response. There can be many middleware, each of which can intercept the request in the pipeline, and it can decide whether to transfer the request to the next middleware.

Asp.net core provides an IApplicationBuilder interface to register middleware with asp.net pipeline requests, which is a typical AOP application.

Each middleware can operate before and after the request. After the request processing is completed, it is passed to the next request.

The operation mode of middleware

By default, the execution order of the middleware is based on the order registered in the public void Configure (IApplicationBuilder app) {} method in the Startup.cs file.

There are about three ways to register "middleware" in a pipe.

It is used by 1.app.Use (), native IApplicationBuilder interface, registration, etc.

2.app.Run (), an extension method, requires a RequestDelegate delegate that contains context information for Http and has no next parameter, because it is always executed at the last step of the pipeline.

3.app.Map (), which is also an extension method, is similar to MVC routing and is generally used for the processing of special request paths. Such as: www.example.com/token, etc.

The above Run,Map is also called Use, which is an extension of the IApplicationBuilder interface. If you think the name is not accurate enough, then the following extension method is the authentic registration middleware and is the most powerful.

App.UseMiddleware (), yes, this is it. Why is it powerful? Because it provides not only the function of registration middleware, but also the function of dependency injection (DI), which will be used in most cases.

The difference between middleware (Middleware) and filter (Filter)

Students who are familiar with the MVC framework should know that MVC also provides five filters for us to use to process the code that needs to be executed before and after the request. They are AuthenticationFilter,AuthorizationFilter,ActionFilter,ExceptionFilter,ResultFilter.

According to the description, you can see that the functions of middleware and filters are similar, so what's the difference between them? Why do you want to build another middleware?

In fact, filters and middleware have different concerns, that is, if they have different responsibilities, they do different things.

Take a chestnut, the middleware is like the Essynos blade, the filter is like the wrath of the dragon, the soul stick of Terygosa, a warrior holding the wrath of the dragon, Terygosa's soul stick to the battlefield, although there is damage, but you hold the staff damage low, but also reduce the attribute ah.

As two AOP sharp tools, the filter is more suitable for the business, it focuses on the application itself, for example, if you look at ActionFilter and ResultFilter, it interacts directly with your Action,ActionResult, so I have some feelings, such as formatting my output results, and verifying the data of my request ViewModel. There must be no doubt about using Filter. It is part of MVC, it can intercept some information in your Action context, and middleware does not have this ability.

What do we need middleware for?

So, when to use middleware? My understanding is that some of the things that need to be done in the pipeline that are not relevant to the business in our application can be used, such as authentication, Session storage, logging, etc. In fact, our asp.net core project already contains a lot of middleware.

For example, when we create a new asp.net core application, the template generated by default

Public void Configure (IApplicationBuilder app, ILoggerFactory loggerFactory) {app.UseDeveloperExceptionPage (); app.UseStaticFiles (); loggerFactory.AddConsole (); app.UseMvc (routes = > {routes.MapRoute (name: "default", template: "{controller=Home} / {action=Index} / {id?}");});}

Don't bother to download the source code, let's use Reflector to check the source code:

/ / extension method `app.UseDeveloperExceptionPage (); `public static class DeveloperExceptionPageExtensions {/ / Methods public static IApplicationBuilder UseDeveloperExceptionPage (this IApplicationBuilder app) {if (app = = null) {throw new ArgumentNullException ("app");} return UseMiddlewareExtensions.UseMiddleware (app, Array.Empty ());} / / extension method `app.UseStaticFiles (); `public static class StaticFileExtensions {/ / Methods public static IApplicationBuilder UseStaticFiles (this IApplicationBuilder app) {if (app = = null) {throw new ArgumentNullException ("app") } return UseMiddlewareExtensions.UseMiddleware (app, Array.Empty ());}

You can see that app.UseDeveloperExceptionPage (), app.UseStaticFiles (), and so on are all implemented through middleware.

How to customize your own middleware

Background: when we use middleware in our project, we need to share User information with other departments. Platform and subsystem for example, we are developing a subsystem, in which user information, login, registration and other functions are put on the platform, this is a cross-language system, the platform is developed in Java language, users in the access to some pages of the subsystem need to verify whether to log in, other pages do not need to verify whether to log in, so need an authentication system to replace the functions of Identity.

Fortunately, Microsoft has provided us with a set of authentication middleware, under the Microsoft.AspNetCore.Authentication namespace, we just need to expand and add our own functions. How do you do it exactly? Just look at the code.

According to convention, the middleware class needs to have an Invoke method with a signature of public async Task Invoke (HttpContext context) {}. Here is an example class of middleware:

Public class RequestLoggerMiddleware {private readonly RequestDelegate _ next; private readonly ILogger _ logger; public RequestLoggerMiddleware (RequestDelegate next, ILoggerFactory loggerFactory) {_ next = next; _ logger = loggerFactory.CreateLogger ();} public async Task Invoke (HttpContext context) {_ logger.LogInformation ("Handling request:" + context.Request.Path); await _ next.Invoke (context); _ logger.LogInformation ("Finished handling request.");}}

After understanding the above convention, we began to define our own middleware Class.

We need a flowchart to sort out the logic so that we can write code more clearly.

A requirement of the platform is that after our subsystem exits, users should call an interface of the platform to inform them that they want to do some follow-up business.

OK, start the code.

First of all, create a PlatformAuthoricationMiddleware, which inherits from the class AuthenticationMiddleware under Microsoft.AspNetCore.Authentication. Since AuthenticationMiddleware has implemented the Invoke function, we only need to override some of its methods. Wait, it seems that we still need some configuration, such as the ReturnUrl in the flow chart, the Cookie key value of the platform, the interface address of the platform to verify the validity of the user, and so on.

Set up an Options class to configure the settings, we name it: PlatformAuthenticationOptions, inherit AuthenticationOptions, and implement the IOptions interface, so you can configure it directly in Startup.

We only need to rewrite the CreateHandler method in AuthenticationMiddleware, and we can implement our middleware function in Handler.

Then create a processed Handler class, named PlatformAuthenticationHandler, which is inherited from AuthenticationHandler to handle calls in the request.

At this point, the classes that our core needs have been built, and all that's left is to populate the code.

1. Override the HandleAuthenticateAsync () method in PlatformAuthenticationHandler to control the main flow.

two。 Override the FinishResponseAsync () method in PlatformAuthenticationHandler to perform the storage operation of Session.

3. Override the HandleSignOutAsync () method in PlatformAuthenticationHandler to control logout, because we need to tell the platform to do something else after the user logs out.

4. Override the HandleUnauthorizedAsync () method in PlatformAuthenticationHandler to perform an unauthenticated operation.

Finally, we need an extension class to register our middleware with the pipeline in an extension method.

Public static class MiddlewareExtensions {public static IApplicationBuilder UsePlatformAuthentication (this IApplicationBuilder app) {if (app = = null) {throw new ArgumentNullException (nameof (app));} return app.UseMiddleware ();} public static IApplicationBuilder UsePlatformAuthentication (this IApplicationBuilder app, CookieAuthenticationOptions options) {if (app = = null) {throw new ArgumentNullException (nameof (app));} if (options = = null) {throw new ArgumentNullException (nameof (options)) } return app.UseMiddleware (Options.Create (options));}}

In Startup, it is app.UsePlatformAuthentication ()

Public void Configure (IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {loggerFactory.AddConsole (Configuration.GetSection ("Logging")); / / register PlatformAuthentication middleware app.UsePlatformAuthentication (new PlatformAuthenticationOptions () {UserSessionStore = new UserSessionStore (),}); app.UseMvc ();} above is the middleware that Xiaobian shared for you how to use ASP.NETCore. If you happen to have similar doubts, please refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report