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

What is the concept of ASP.NET Core middleware and pipeline

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Today, I would like to share with you the relevant knowledge of what the concept of ASP.NET Core middleware and pipeline is. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article.

In ASP.NET Core, pipeline is usually used to deal with HTTP requests, and many middleware (processing logic) can be mounted in the pipeline container to process HTTP requests. Each middleware has the right to decide whether to execute the next middleware or respond directly. This mechanism enables HTTP requests to be well processed and controlled layer by layer, and it is very convenient to deal with the hierarchy clearly. The schematic diagram is as follows:

In order to illustrate the concept of pipeline and middleware again, to take an official example of authority verification, the middleware AMagi B is mounted sequentially in the pipeline container, An is the permission verification middleware, and B can be executed only through the permission verification of A. if it does not pass the verification of A, A has the right to interrupt the pipeline processing and directly return the corresponding error prompt such as 401, etc. The serial recursive execution mode that must be called by the previous node is pipeline, and each node is the middleware or intermediate component. Now let's look at how to use middleware in ASP.NET Core and manage your own HTTP pipeline

Environment configuration and Startup

Before we can understand the middleware, we need to know how the class Startup works. Let's take the following code as an example:

/ the entry class of the web host / public class Startup {/ / add the service item to the container This method will be called by runtime public void ConfigureServices (IServiceCollection services) {} / configure the HTTP request pipeline / the request pipeline used to build the application can only be used in the Configure method in Startup to provide access to application properties For example, the environment variable / / provides a mechanism for creating logs, public void Configure (IApplicationBuilder app,IHostingEnvironment env,ILoggerFactory loggerFactory) {loggerFactory.AddConsole () If (env.IsDevelopment ()) / / if the development environment is based on the configured environment, the exception error interface {app.UseDeveloperExceptionPage () will be configured. / / throw a detailed exception error interface} / / Pipeline break app.Run (async (context) = > {await context.Response.WriteAsync ("Hello World!");});}}

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

Why does it have to be these two method names?

In fact, the names of these two methods are not prescribed, but they are not arbitrary. They are judged according to the environment variables of the container. Here is the official document "working in multiple environments".

We can learn from the document that Core uses the "ASPNETCORE_ENVIRONMENT" field to describe the current runtime environment name, which is the environment configuration mentioned above. The official preset three environment names are Development (development environment), Staging (test environment), and Production (production environment). If you are using VSCode, you can find the "ASPNETCORE_ENVIRONMENT" field in the launch.json under the .vscode folder, and you will find that it is Development by default. So what's the use of all this?

It is stipulated in Startup that the two methods of configuration service and middleware can be named and called according to the environment name, and the naming rules are ConfigureServices {ENVIRONMENT} and Configure {ENVIRONMENT}. For example, ASPNETCORE_ENVIRONMENT = "Development", ConfigureServices and Configure can be written as ConfigureServicesDevelopment and ConfigureDevelopment, as well as others. This allows you to configure ASPNETCORE_ENVIRONMENT to decide which configuration method to call.

What is the environment of ConfigureServices and Configure?

ConfigureServices and Configure are just like default in the Switch statement. If no method name is found that matches the environment name, both methods are called. If Development is configured but no ConfigureServicesDevelopment is given, ConfigureServices will be executed and an exception will be thrown if none are given.

Must it be set to the default environment name?

The parameter name of the environment name configuration does not have to be a default value, you can write one yourself, such as LogEnv and so on.

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

/ the entry class of the web host / public class Startup {/ / add the service item to the container This method will be called by runtime to configure the HTTP request pipeline / public void ConfigureLogHelp (IApplicationBuilder app) {app.Run (async (context) = > {await context.Response.WriteAsync ("Hello World-ConfigureLogHelp") in the Log environment. }); configure HTTP request pipeline / public void ConfigureDevelopment (IApplicationBuilder app) {app.Run (async (context) = > {await context.Response.WriteAsync ("Hello World-ConfigureDevelopment");}) under the development environment } / by default configure the HTTP request pipeline / that is used to build the application's request pipeline. You can only use / to provide access to application properties in the Configure method in Startup For example, the environment variable / / provides a mechanism for creating logs: public void Configure (IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {/ / app.Run (async (context) = > {await context.Response.WriteAsync ("Hello World!")) });}

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 also lies in what kind of CSS and JS should be referenced at the front end. We will discuss these later in the MVC chapter. Bloggers who want to know can read the official documents.

Pipeline configuration and Startup

After talking about the relationship between environment configuration and Startup, let's come back to talk about pipelines. Now let's talk about Configure {ENVIRONMENT} and Configure for short.

The Configure method is used to configure the middleware-to-middle pipeline container (IApplicationBuilder), so this method must include 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 following figure is from the Chinese document of ASP.NET Core)

It should be mentioned that the environment name we mentioned above can be obtained in IHostingEnvironment, and the preset is officially encapsulated. Of course, you can reconstruct it to encapsulate your own environment name judgment.

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

The a.Run method makes it possible to short-circuit the pipe, which, as the name implies, terminates the downward execution of the pipe without calling the next () delegate, so the Run method is best executed at the end of the pipe, as in the following code:

/ / configure HTTP request pipeline / public void ConfigureDevelopment (IApplicationBuilder app) {app.Run (async (context) = > {await context.Response.WriteAsync ("Hello World-ConfigureDevelopment");}) in the development environment App.Run (async (context) = > {await context.Response.WriteAsync ("Hello World-ConfigureDevelopment will not be executed");});}

Execution result:

B.Use will not actively short-circuit the entire HTTP pipeline, but it will not actively call the next middleware, so it must call await next.Invoke () itself. If you do not use this method to call the next middleware, then the effect of Use is actually the same as Run. Let's look at the normal code:

/ configure HTTP request pipeline / 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 implementation results are as follows:

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

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

/ configure HTTP request pipeline / public void ConfigureDevelopment (IApplicationBuilder app) {var order = ""; app.Use (async (context, next) = > {order = $"{order} | Use start" in the development environment / / remove the display 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 results are as follows:

It can be found that the Run middleware is not executed, but only the Use middleware is executed. So without explicitly calling the next middleware, the effect is the same as in Run, which shorts the pipeline.

C.Map can route the middleware according to the URL provided. The following code determines that some middleware logic will be executed when "/ test" is accessed in URL:

/ / configure HTTP request pipeline / public void ConfigureDevelopment (IApplicationBuilder app) {app.Map ("/ test", HandleMapTest) in the development environment } / maptest processing method / public void HandleMapTest (IApplicationBuilder app) {app.Run (async (context) = > {await context.Response.WriteAsync ("HandleMapTest Handler");});}

The results are as follows:

If you visit / test, the corresponding middleware will be executed, otherwise it will not be executed.

MapWhen is an extension of Map's condition judgment, which can be used to determine whether a certain middleware is executed when a condition is appropriate, such as executing a middleware when carrying a parameter name or vice versa. The code is as follows:

/ / configure HTTP request pipeline / public void ConfigureDevelopment (IApplicationBuilder app) {app.MapWhen (context = > {return context.Request.Query.ContainsKey ("username");}, HandleUserName) under the development environment App.Run (async context = > {await context.Response.WriteAsync ("default ext");});} / / public void HandleUserName (IApplicationBuilder app) {app.Run (async context = > {await context.Response.WriteAsync ("UserName Map")) });}

The results are as follows:

These are all the contents of the article "what is the concept of ASP.NET Core Middleware and Pipeline". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to 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