Learn more about the. Net Core Web API Development Series "13": Middleware (middleware)

Source: Internet
Author: User

Series Catalogue

Learn more about the. Net Core WEB API Development Series Catalog

The source code involved in this series: Https://github.com/seabluescn/Blog_WebApi

I. Overview

This article describes how to use middleware (middleware).

Second, the preliminary exercise

Write a few middleware first

 Public classDemoamiddleware {Private ReadOnlyrequestdelegate _next; Private ReadOnlyILogger _logger;  PublicDemoamiddleware (requestdelegate Next, ilogger<demoamiddleware>logger) {_next=Next; _logger=logger; }         Public AsyncTask Invoke (HttpContext context) {_logger. Loginformation ("(1) demoamiddleware.invoke front"); await_next (context); _logger. Loginformation ("[1] demoamiddleware:invoke back"); }           }   Public classDemobmiddleware {Private ReadOnlyrequestdelegate _next; Private ReadOnlyILogger _logger;  PublicDemobmiddleware (requestdelegate Next, ilogger<demobmiddleware>logger) {_next=Next; _logger=logger; }         Public AsyncTask Invoke (HttpContext context) {_logger. Loginformation ("(2) Demobmiddleware.invoke part1"); await_next (context); _logger. Loginformation ("[2] demobmiddleware:invoke part2"); }          }     Public classRequestrecordmiddleware {Private ReadOnlyrequestdelegate _next; Private ReadOnlyILogger _logger;  PublicRequestrecordmiddleware (requestdelegate Next, ilogger<requestrecordmiddleware>logger) {_next=Next; _logger=logger; }         Public AsyncTask Invoke (HttpContext context) {_logger. Loginformation ("(3) Requestrecordmiddleware.invoke"); String URL=context.            Request.Path.ToString (); _logger. Loginformation ($"URL: {URL}"); await_next (context); _logger. Loginformation ("[3] Requestrecordmiddleware:invoke next"); _logger. Loginformation ($"StatusCode: {context. Response.statuscode}"); }           }

The first two of the above middleware did not do any serious work, print some log information, a third to do a bit of work, it printed the user input URL, and print the return to the client status code.

Middleware needs to be enabled to work with the middleware.

    Public classStartup { PublicStartup (iconfiguration configuration) {Configuration=configuration; }         PublicIConfiguration Configuration {Get; } //This method gets called by the runtime. Use this method to add services to the container.         Public voidconfigureservices (iservicecollection services) {services. Addmvc ();        }        //This method gets called by the runtime. Use this method to configure the HTTP request pipeline.         Public voidConfigure (Iapplicationbuilder app, Ihostingenvironment env, Iloggerfactory loggerfactory) {app.            Useunifyexception (); app. Usemiddleware <DemoAMiddleware> (); App.                       Usemiddleware<demobmiddleware> (); App. Usemiddleware<requestrecordmiddleware>(); app.            Usestaticfiles (); App.        Usemvcwithdefaultroute (); }

With the extension method, we transform the middleware's enabler code:

 Public Static classrequestrecordmiddlewareextensions { Public StaticIapplicationbuilder Userequestrecord ( ThisIapplicationbuilder Builder) {            if(Builder = =NULL)            {                Throw NewArgumentNullException ("Builder is null"); }            returnBuilder. Usemiddleware<requestrecordmiddleware>(); }    }

The code is now enabled by: App. Usemiddleware<requestrecordmiddleware> ();

Can be modified as: app. Userequestrecord ();

The implementation effect has not changed. It can be seen that the following code is the use of middleware.

App. Usestaticfiles (); app. Usemvcwithdefaultroute ();

  

I understand that the middleware is similar to the workers in the Workshop assembly line, the operation of the parts is HttpContext, each person is responsible for two processes, I define them as "the front process" and "after the process", through the Code _next (context); To isolate the two processes, the order of processing requires special attention, according to the order of the middleware registration process "the previous process", processing completed, and then in reverse order to deal with the "back process", if a middleware does not call _next (context), then will not call the subsequent middleware, So the order in which middleware is enabled requires special consideration.

The order of information from the three middleware output to the console in the above code is as follows:

(1)

(2)

(3)

"3"

"2"

"1"

Personally, the "forward process" should focus on the request, "after-work process" should focus on the treatment of response.

Third, do a MVC-like middleware

Let's make a middleware that returns some content to the client:

 Public classMymvcmiddleware {Private ReadOnlyrequestdelegate _next; Private ReadOnlyILogger _logger;  PublicMymvcmiddleware (requestdelegate Next, ilogger<demoamiddleware>logger) {_next=Next; _logger=logger; }         Public AsyncTask Invoke (HttpContext context) {varstr ="hello,world!"; awaitcontext.                  Response.writeasync (str); }           }

This middleware simply returns a fixed string, and we can also invoke the provided method of a controller.

    Public classMymvcmiddleware {Private ReadOnlyrequestdelegate _next; Private ReadOnlyILogger _logger;  PublicMymvcmiddleware (requestdelegate Next, ilogger<demoamiddleware>logger) {_next=Next; _logger=logger; }         Public AsyncTask Invoke (HttpContext context) {
varobj = context. Requestservices.getrequiredservice<articlecontroller>(). Getarticlelist (); varstr =jsonconvert.serializeobject (obj); awaitcontext. Response.writeasync (str); } }
Articlecontroller is defined as follows:
     Public classArticlecontroller:controller {Private ReadOnlySalescontext _context; Private ReadOnlyILogger _logger; Private ReadOnlyIMemoryCache _cache;  PublicArticlecontroller (Salescontext context, ilogger<articlecontroller>logger, IMemoryCache memorycache) {_context=context; _logger=logger; _cache=MemoryCache; } [HttpGet] Publicresultobject getarticlelist () {_logger. Loginformation ("==getarticlelist=="); List<Article> articles =_context. Articles. Asnotracking ().            ToList (); return NewResultobject {result=articles}; }      }

To use the controller in the middleware by relying on it, you need to register it with the DI container:

 Public void configureservices (iservicecollection services) {       services. addscoped<ArticleController>();}

The above middleware realizes an article information query function, if in this middleware first judge the path, then according to the different path calls different Contorller provides the service, can form a simple MVC middleware.

Iv. use of middleware

The use of middleware embodies the AOP (tile-oriented) programming idea, without modifying the existing code, by adding some middleware to implement some specific logic, can do a lot of things, such as:

URL rewriting

Cache processing

Exception handling

User authentication

V. Registration Order of Middleware

The previous article mentions that the registration order of middleware is more important, the recommended order is as follows:

1. Exception/error handling
2. static file server
3. Authentication
4.MVC

Learn more about the. Net Core Web API Development Series "13": Middleware (middleware)

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.