ASP. NET Core, asp. netcore

Source: Internet
Author: User

ASP. NET Core, asp. netcore

Let's discuss an ASP. NET Core is an important concept pipeline and middleware, in ASP. in NET Core, pipelines are usually used to process HTTP requests. Many middleware (processing logic) can be mounted in the pipeline container to process HTTP requests in tandem, each middleware has the right to decide whether to execute the next middleware or directly make a response. This mechanism makes it easy to process and control HTTP requests layer by layer and process them in a clear and hierarchical manner. As follows:

  

To describe the concept of MPs queue and middleware again, an official permission verification example is provided. Middleware A and B are mounted to the MPs queue container in order, and middleware A is the permission verification middleware, B can only be executed if A passes the permission verification of A. If A does not pass the authentication of A, A has the right to interrupt pipeline processing and directly return the corresponding error message, such as 401. In this way, the serial Recursive Execution method that must be called by the previous node is pipeline, and each node is a middleware or intermediate component. Now let's take a look at how to use middleware in ASP. NET Core and manage your own HTTP Pipeline

 

  Environment configuration and Startup

Before learning about middleware, we need to first know how the Startup class works. The following code is used as an example:

/// <Summary> /// portal class of the web host /// </summary> public class Startup {// Add the service item to the container, this method will be called by runtime public void ConfigureServices (IServiceCollection services) {}/// <summary> /// configure the HTTP request pipeline // </summary> /// <param name = "app"> is used to construct the application request the MPs queue can only use the </param> // <param name = "env"> method in the Configure method of Startup to access application properties, for example, the Environment Variable </param> /// <param name = "loggerFactory"> provides a log creation mechanism </param> public void Configure (IAppl IcationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {loggerFactory. addConsole (); if (env. isDevelopment () // Based on the configured environment as the development environment, the configuration throws an exception error interface {app. useDeveloperExceptionPage (); // throw a detailed error page} // pipeline breaker app. run (async (context) =>{ await context. response. writeAsync ("Hello World! ");});}}

You can see that there are two methods in Startup. cs: one is to Configure ConfigureServices from the interface service to the pipeline container, and the other is to Configure of the pipeline middleware.

  Why must these two method names be used?

In fact, the two method names are not specified, but they are not specified. They are determined based on the container's environment variables, the official document "work in multiple environments" is provided here.

We can understand in this document that Core uses the "ASPNETCORE_ENVIRONMENT" field to describe the current running environment name. This is the environment configuration mentioned above. The three environment names preset by the official website areDevelopment(Development Environment ),Staging(Test environment ),Production(Production environment), if you are using VSCode, you can. launch in the vscode folder. if the "ASPNETCORE_ENVIRONMENT" field is found in json, the default value is Development. What is the purpose of this field?

  

  In Startup, you can name and choose to call the configuration service and middleware methods based on the ENVIRONMENT name. The naming rules are ConfigureServices {ENVIRONMENT} and Configure {ENVIRONMENT}.For example, ASPNETCORE_ENVIRONMENT ="Development", ConfigureServices and Configure can be written as ConfigureServices.DevelopmentAnd ConfigureDevelopment,The same applies to others. In this way, you can determine which configuration method to call by configuring ASPNETCORE_ENVIRONMENT.

  In what environment is ConfigureServices and Configure?

ConfigureServices and Configure are the same as default in the Switch statement. If no method name conforming to the Environment name is found, the two methods are called. If Development is configured but ConfigureServicesDevelopment is not provided, ConfigureServices will be executed. If none of them exist, an exception will be thrown.

  Must it be set to the default environment name?

  The parameter name configured for the Environment name does not need to be a preset value. You can write one by yourself, such as LogEnv.

Next, let's take a look at the implementation code:

/// <Summary> /// portal class of the web host /// </summary> public class Startup {// Add the service item to the container, this method will be called by runtime public void ConfigureServices (IServiceCollection services) {} // <summary> // configure the HTTP request pipeline in the Log environment // </summary> // <param name = "app"> </param> public void ConfigureLogHelp (IApplicationBuilder app) {app. run (async (context) =>{ await context. response. writeAsync ("Hello World-ConfigureLogHelp ");});}/// <Summary> // configure the HTTP request pipeline in the development environment /// </summary> /// <param name = "app"> </param> public void ConfigureDevelopment (IApplicationBuilder app) {app. run (async (context) =>{ await context. response. writeAsync ("Hello World-ConfigureDevelopment ");});} /// <summary> /// configure the HTTP request pipeline by default /// </summary> /// <param name = "app"> used to build the application request pipeline. You can only use </param> // <param name = "env"> In the Configure method of Startup to access application attributes, for example, the Environment Variable </param> /// <param name = "loggerFactory"> provides a log creation mechanism </param> public void Configure (IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {// pipeline breaker app. run (async (context) =>{ await context. response. writeAsync ("Hello World! ");});}Startup. cs

When ASPNETCORE_ENVIRONMENT ="Development"

  

When ASPNETCORE_ENVIRONMENT = "LogHelp"

  

The advantage of this is that you can write your own test configuration without affecting others or the development process. Of course, the role of the environment is what kind of CSS and JS should be referenced at the front end. We will discuss these issues later in the MVC chapter. For more information, see the official documentation.

 

  MPs queue configuration and Startup

After talking about the relationship between environment configuration and Startup, let's come back and talk about the MPs queue. Now let's talk about Configure {ENVIRONMENT} This method is short for Configure.

The Configure method is used to Configure the middleware to the pipeline container (IApplicationBuilder). Therefore, this method must contain an IApplicationBuilder parameter to accept the pipeline container, which is convenient for developers to Configure. Of course, he can also accept other optional parameters for developers to use as follows:

(Note: the source is the Chinese Document of ASP. NET Core)

  

We need to mention that the Environment name we mentioned above can be obtained in IHostingEnvironment, and the official judgment encapsulation of the preset value is also made, of course, you can refactor it to encapsulate your own environment name judgment.

 

The HTTP pipeline container uses three extended methods to control the routing and mounting of middleware.Run, Map, User.

A.RunThe method will make the pipeline short-circuited. As the name suggests, it means that the next () Delegate will not be called when the pipeline is terminated. Therefore, the Run method should be executed at the end of the pipeline, as shown in the following code:

/// <Summary> /// configure the HTTP request pipeline in the development environment /// </summary> /// <param name = "app"> </param> public void configureDevelopment (IApplicationBuilder app) {app. run (async (context) =>{ await context. response. writeAsync ("Hello World-ConfigureDevelopment");}); app. run (async (context) =>{ await context. response. writeAsync ("Hello World-ConfigureDevelopment will not be executed ");});}

Execution result:

  

 

B.UseDoes not actively short the entire HTTP pipeline, but does not actively call the next middleware. You must call await next on your own. invoke (); if you do not Use this method to call the next middleware, the effect of Use at this time is actually the same as that of Run. Let's look at the normal code:

/// <Summary> /// configure the HTTP request pipeline in the development environment /// </summary> /// <param name = "app"> </param> public void configureDevelopment (IApplicationBuilder app) {var order = ""; app. use (async (context, next) =>{ order = $ "{order} | Use start"; await next. invoke (); order = $ "{order} | Use end" ;}); app. run (async context => {await context. response. writeAsync ($ "{order} | Run ext ");});}

The execution result is as follows:

  

As you can see, Use end is not executed, because Run is used when the next middleware is called, and the pipeline is terminated.

Let's take a look at the code when next. Invoke () is not explicitly called:

/// <Summary> /// configure the HTTP request pipeline in the development environment /// </summary> /// <param name = "app"> </param> public void configureDevelopment (IApplicationBuilder app) {var order = ""; app. use (async (context, next) =>{ order = $ "{order} | Use start"; // remove the display and call the next middleware // await next. invoke (); order = $ "{order} | Use end"; await context. response. writeAsync (order) ;}); app. run (async context => {await context. response. writeAsync ($ "{order} | Run ext ");});}

The result is as follows:

  

We can find that the Run middleware is not executed, but simply executed the Use middleware. Therefore, if the next middleware is not explicitly called, the short-circuit of the pipeline will be triggered if the effect is the same as that of running.

 

C.MapThe middleware can be routed based on the provided URL. The following code judges that a middleware logic will be executed when accessing "/test" in the URL:

/// <Summary> /// configure the HTTP request pipeline in the development environment /// </summary> /// <param name = "app"> </param> public void configureDevelopment (IApplicationBuilder app) {app. map ("/test", HandleMapTest) ;}/// <summary> /// maptest processing method /// </summary> public void HandleMapTest (IApplicationBuilder app) {app. run (async (context) =>{ await context. response. writeAsync ("HandleMapTest Handler ");});}

The result is as follows:

  

If you access/test, the corresponding middleware will be executed. Otherwise, the middleware will not be executed.

  MapWhenIt is an extension method of Map's condition judgment. It can be used to execute a middleware when a condition is suitable. For example, when a parameter name is carried, execute a middleware or vice versa. The Code is as follows:

/// <Summary> /// configure the HTTP request pipeline in the development environment /// </summary> /// <param name = "app"> </param> public void configureDevelopment (IApplicationBuilder app) {app. mapWhen (context => {return context. request. query. containsKey ("username") ;}, HandleUserName); app. run (async context => {await context. response. writeAsync ("default ext") ;}/// <summary >///// </summary> public void HandleUserName (IApplicationBuilder app) {app. run (async context => {await context. response. writeAsync ("UserName Map ");});}

The result is as follows:

  

  

Map can also implement nested routing middleware, which is not described here. You can refer to it here.

This is the introduction of the MPs queue today. I hope it will be helpful to you. If you have any questions, I hope you can correct them more.

 

 

  

  

  

 

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.