A brief discussion on ASP and project actual practice of net Core middleware

Source: Internet
Author: User
Objective

This article is in the development of our own projects in the actual use, compared to the actual application, is a deep use of middleware, not a simple Hello world.

The role of middleware (middleware)

We know that any web framework is encapsulating HTTP requests into a single pipeline, and each request is a pipeline of operations that eventually arrive in the code we write. Then the middleware is a component in the application pipeline that intercepts the request process for some other processing and response. Middleware can have many, each middleware can intercept requests in the pipeline, it can decide whether to transfer the request to the next middleware.

ASP. NET core provides a Iapplicationbuilder interface for registering middleware with ASP. NET pipeline request, middleware is a typical AOP application.
Each middleware can be manipulated before and after the request. The request processing is completed and passed to the next request.

How the Middleware Works

By default, the order in which the middleware executes is performed according to the order in which the Startup.cs file is registered in the public void Configure (Iapplicationbuilder app) {} method.

There are about 3 ways to register "middleware" in a pipeline

1.app. Use (), Iapplicationbuilder interface native provided, registration, etc. are used it.

2.app. Run () is an extension method that requires a requestdelegate delegate that contains the context information for the HTTP, without the next parameter because it is always executed at the last step of the pipeline.

3.app. Map () is also an extension method, similar to the MVC route, and is typically handled by some special request paths. such as: Www.example.com/token and so on.

The above run,map is also called the use of the Iapplicationbuilder interface expansion, if you think the name is not accurate, then the following extension method is the authentic registration middleware, but also the most powerful.

App. Usemiddleware<> (), yes, that's it. Why do you say powerful? Because it not only provides the function of registering middleware, but also provides the function of dependency injection (DI), which is used in most cases later.

The difference between middleware (middleware) and filters (filter)

Students familiar with the MVC framework should know that MVC also provides 5 filters for the code we need to execute before and after the request. Authenticationfilter,authorizationfilter,actionfilter,exceptionfilter,resultfilter, respectively.

According to the description, you can see that the middleware and filter functions are similar, then what is the difference between them? Why do we have to do a middleware again?
In fact, filters and middleware their focus is not the same, that is, the responsibility is different, do things differently.

For a chestnut, middleware like a azzinoth war blade, filter like the Dragon's Wrath, the soul of the Wolf, you a warrior with the Dragon's Wrath, the soul of the arms of the Muay Thai to kill in the battlefield, although there are injuries, but you take the staff hurt low do not say, but also reduce the properties ah.

As a two AOP tool, the filter is more business-focused, it focuses on the application itself, such as you see Actionfilter and Resultfilter, it is directly and your action,actionresult interaction, is not close to you feel, Then I have some example of the output of my format, the ViewModel of my request for data validation, it must be using filter is undoubtedly. It's part of MVC, it can intercept some information about your action context, and middleware doesn't have that ability.

What situation do we need middleware

So when is middleware used? My understanding is that some of the things that need to be done in the pipeline, such as authentication, session storage, logging, and so on, are in our applications and business relationships are small. In fact, our ASP. NET core project itself already contains a lot of middleware.

For example, when creating a new ASP. NET core application, the default generated template

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}");  });

Too lazy to download the source code, we use reflector to view 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<developerexceptionpagemiddleware> (app, Array.Empty<object > ());}  }

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<staticfilemiddleware> (App, array.empty<object> ());}  }

You can see the app. Usedeveloperexceptionpage (), app. Usestaticfiles () and so on are all implemented through middleware.

How to customize your own middleware

Background: The scenario in which our project uses middleware is the need to share user information with other departments. To the platform and subsystem example, we are developing a subsystem, wherein the user information, login, registration and other functions are placed on the platform, which is a multi-lingual system, the platform is the Java language development, users in the access to some of the subsystem's pages need to verify whether to log on, Other pages do not require authentication to log in, so an authentication system is required in place of the identity feature.

Fortunately, Microsoft has provided us with a set of authentication middleware, in the Microsoft.AspNetCore.Authentication namespace, we just need to expand, add their own features on the line. How do you do it specifically? Look directly at the code.

As a conventional practice, the middleware class needs to have an Invoke method, the signature is public async Task Invoke (HttpContext context) {}, and the following is an example class for a middleware:

public class requestloggermiddleware{  private readonly requestdelegate _next;  Private ReadOnly ILogger _logger;   Public Requestloggermiddleware (Requestdelegate Next, iloggerfactory loggerfactory)  {    _next = next;    _logger = loggerfactory.createlogger<requestloggermiddleware> ();  }   Public Async Task Invoke (HttpContext context)  {    _logger. Loginformation ("Handling Request:" + context.) Request.path);    Await _next. Invoke (context);    _logger. Loginformation ("Finished handling request.");}  

Having understood the above conventions, we began to define our own middleware class.

We need a flowchart to clear up the logic, so that the idea of writing code is clearer.

The platform has a requirement that the user after our subsystem exits, to invoke the platform of an interface to notify them that they want to do some follow-up business.

OK, start the code.

First create a platformauthoricationmiddleware, It inherits from the class Authenticationmiddleware under Microsoft.AspNetCore.Authentication, because Authenticationmiddleware has implemented the Invoke function, so we just need to rewrite (override) Some of the methods inside it are available. Wait, we seem to need some configuration, such as the ReturnUrl in the flowchart, the key value of the platform's cookie, and the interface address of the platform to verify the user's legitimacy.

Set up an options class to configure the settings, we take the name: Platformauthenticationoptions, Inherit authenticationoptions, and implement the Ioptions<t> interface, This way you can configure it directly in startup.

We just need to rewrite the Createhandler method in Authenticationmiddleware, we can implement the function of our middleware in handler.

It then creates a processing handler class, named Platformauthenticationhandler, that inherits the call that Authenticationhandler<toptions> uses to process the request.

At this point, our core needs of the class has been established, the rest is to fill the code.

1. Rewrite the Handleauthenticateasync () method in Platformauthenticationhandler to control the main process.

2. In Platformauthenticationhandler, rewrite the Finishresponseasync () method to perform the session storage operation.

3. Rewrite the Handlesignoutasync () method in Platformauthenticationhandler to control the logout, because after the user has logged out we have to notify the platform to do some other things.

4. In Platformauthenticationhandler, rewrite the Handleunauthorizedasync () method to perform an unauthenticated operation.

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

public static class middlewareextensions{public  static Iapplicationbuilder useplatformauthentication (this Iapplicationbuilder app) {    if (app = = null) {      throw new ArgumentNullException (nameof (APP));    }     Return app. Usemiddleware<platformauthenticationmiddleware> ();  }   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<platformauthenticationmiddleware> (Options.create (Options));}  }

In Startup 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 ();}

Now, the implementation of our middleware core business process has come out, I have not much space to paste the code, will affect the reading, interested in the implementation of the specific friends can go to the following address to view the code, there are specific process comments.

The above is the whole content of this article, I hope that everyone's learning to help, more on the ASP. NET Core middleware detailed and project related articles please pay attention to topic.alibabacloud.com!

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.