In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the knowledge of "what is ASP.NET Core middleware Middleware". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
What is middleware (Middleware)?
Middleware is software that is assembled into an application pipeline to handle requests and responses. Each component:
Select whether to pass the request to the next component in the pipeline.
Work can be performed before and after invoking the next component in the pipeline.
Request delegation (Request delegates) is used to build a request pipeline to process each HTTP request.
Request the delegate to be configured using Run,Map and Use extension methods. A separate request delegate can be specified as an inline anonymous method (called inline middleware), or it can be defined in a reusable class. These reusable classes and inline anonymous methods are middleware or middleware components. Each middleware component in the request process is responsible for invoking the next component in the pipeline and, if appropriate, short-circuiting the link.
Migrating HTTP modules to middleware explains the difference between the request pipeline in ASP.NET Core and previous versions (ASP.NET) and provides more middleware examples.
Create a middleware pipe using IApplicationBuilder
The ASP.NET Core request process consists of a series of request delegates, as shown in the following figure (the execution process follows the black arrow):
Each delegate can perform actions before and after the next delegate. The delegate can also decide not to pass the request to the next delegate, which is called a short circuit of the request pipeline. A short circuit is usually desirable because it avoids unnecessary work. For example, a middleware in a static file can return a request for a static file and short-circuit the rest of the pipe. Exception handling delegates need to be called early in the pipeline, so they can catch exceptions from later pipes.
Perhaps the simplest is for the ASP.NET Core application to set up a request delegate to handle all requests. This case does not contain the actual request pipeline. Instead, an anonymous method is called for each HTTP request.
Using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.Http;public class Startup {public void Configure (IApplicationBuilder app) {app.Run (async context = > {await context.Response.WriteAsync ("Hello, World!");});}}
The first app.Run delegate terminates the pipeline.
The code is as follows:
Through browser access, it was found that the pipe was indeed terminated at the first app.Run.
You can connect multiple request delegates to the app.Use. The next parameter represents the next delegate in the pipeline. Remember, you can end the pipeline by not calling the next parameter. You can usually perform actions before and after the next delegate, as shown in the following example:
Public class Startup {public void Configure (IApplicationBuilder app) {app.Use (async (context, next) = > {await context.Response.WriteAsync ("before entering the first delegate to execute the next delegate\ r\ n") / / call the next delegate in the pipeline await next.Invoke (); await context.Response.WriteAsync ("after the first delegate executes the next delegate\ r\ n");}) App.Run (async context = > {await context.Response.WriteAsync ("enter the second delegate\ r\ n"); await context.Response.WriteAsync ("Hello from 2nd delegate.\ r\ n"); await context.Response.WriteAsync ("end the second delegate\ r\ n") );}}
Using the browser to access has the following results:
You can see that the execution order of the request delegate follows the above flowchart.
Note:
Do not call next.Invoke after the response is sent to the client. After the response starts, changes to the HttpResponse will throw an exception. For example, setting response headers, status codes, and other changes will throw an exception. The response body is written after the call to next.
Could lead to protocol violations. For example, the write exceeds the content length described by content-length.
It may break the format of the response content. For example, write the HTML footer to the CSS file.
HttpResponse.HasStarted is a useful hint to indicate whether a response header has been sent and / or the body has been written.
Sequence
In Startup. The order in which middleware components are added to the Configure method defines the order in which they are invoked on requests and the reverse order of responses. This sort is critical for security, performance, and functionality.
The Startup.Configure method (shown below) adds the following middleware components:
Exception / error handling
Static file service
Identity authentication
MVC
Public void Configure (IApplicationBuilder app) {app.UseExceptionHandler ("/ Home/Error"); / / Call first to catch exceptions / / thrown in the following middleware. App.UseStaticFiles (); / / Return static files and end pipeline. App.UseAuthentication (); / / Authenticate before you access / / secure resources. App.UseMvcWithDefaultRoute (); / / Add MVC to the request pipeline.}
In the above code, UseExceptionHandler is the first middleware component to be added to the pipe, so it catches any exceptions that occur in subsequent calls.
Static file middleware is called in advance in the pipeline, so requests and short circuits can be handled without going through the remaining components. Static file middleware does not provide authorization checks. Any documents provided by it, including those under wwwroot, are public.
If the request is not processed by the static file middleware, it is passed to the Identity middleware (app.UseAuthentication) that performs authentication. Identity does not short-circuit unauthenticated requests. Although an authentication request occurs, authorization (and denial) occurs only after MVC selects a specific Razor page or controller and action.
Authorization (and denial) occurs only after MVC selects a specific Razor page or Controller and Action.
The following example demonstrates the middleware order, where requests for static files are processed by static file middleware before responding to compression middleware. Static files are not compressed in the order of middleware. The MVC response from UseMvcWithDefaultRoute can be compressed.
Public void Configure (IApplicationBuilder app) {app.UseStaticFiles (); / / Static files not compressed app.UseResponseCompression (); app.UseMvcWithDefaultRoute ();} Use, Run, and Map
You can configure HTTP pipes using Use,Run and Map. The Use method can short-circuit the pipe (that is, the next request delegate may not be called). The Run method is a convention, and some middleware components may be exposed to the Run [Middleware] method that runs at the end of the pipe. The Map* extension is used as a convention for branch pipes. The mapping branches the request pipeline based on the matching of the given request path, and executes the branch if the request path starts with a given path.
Public class Startup {private static void HandleMapTest1 (IApplicationBuilder app) {app.Run (async context = > {await context.Response.WriteAsync ("MapTest1");});} private static void HandleMapTest2 (IApplicationBuilder app) {app.Run (async context = > {await context.Response.WriteAsync ("MapTest2");}) } public void Configure (IApplicationBuilder app) {app.Map ("/ map1", HandleMapTest1); app.Map ("/ map2", HandleMapTest2); app.Run (async context = > {await context.Response.WriteAsync ("Hello from non-Map delegate.
");})
The following table shows the requests and responses using http://localhost:19219 from the previous code:
Request response localhost:1234Hello from non-Map delegate.localhost:1234/map1Map Test 1localhost:1234/map2Map Test 2localhost:1234/map3Hello from non-Map delegate.
When Map is used, matching path segments are removed from HttpRequest.Path and appended to Http Request.PathBase for each request.
MapWhen requests the pipeline based on the result of the given predicate. Any predicate of type Func can be used to map the request to a new branch of the pipe. In the following example, predicates are used to detect the existence of query string variable branches:
Public class Startup {private static void HandleBranch (IApplicationBuilder app) {app.Run (async context = > {var branchVer = context.Request.Query ["branch"]; await context.Response.WriteAsync ($"Branch used = {branchVer}");}) } public void Configure (IApplicationBuilder app) {app.MapWhen (context = > context.Request.Query.ContainsKey ("branch"), HandleBranch); app.Run (async context = > {await context.Response.WriteAsync ("Hello from non-Map delegate.
");})
The following table shows the requests and responses using the above code http://localhost:19219:
Request response localhost:1234Hello from non-Map delegate.localhost:1234/?branch=1Branch used = master
Map supports nesting, for example:
App.Map ("/ level1", level1App = > {level1App.Map ("/ level2a", level2AApp = > {/ / "/ level1/level2a" / /...}); level1App.Map ("/ level2b", level2BApp = > {/ / "/ level1/level2b" / /...});})
Map can also match multiple clips at a time, for example:
App.Map ("/ level1/level2", HandleMultiSeg); built-in middleware
ASP.NET Core comes with the following middleware components:
Middleware description Authentication provides authentication support CORS configuration cross-domain resource sharing Response Caching provides cache response support Response Compression provides response compression support Routing definition and constraint request routing Session provides user session management Static Files provides support for static file and directory browsing services URL Rewriting Middleware provides support for rewriting Url and redirects support for writing middleware
Middleware is usually encapsulated in a class and exposed using extension methods. Look at the following middleware, which sets the Culture of the current request from the query string:
Public class Startup {public void Configure (IApplicationBuilder app) {app.Use ((context, next) = > {var cultureQuery = context.Request.Query ["culture"]; if (! string.IsNullOrWhiteSpace (cultureQuery)) {var culture = new CultureInfo (cultureQuery); CultureInfo.CurrentCulture = culture; CultureInfo.CurrentUICulture = culture } / / Call the next delegate/middleware in the pipeline return next ();}); app.Run (async (context) = > {await context.Response.WriteAsync ($"Hello {CultureInfo.CurrentCulture.DisplayName}");});}}
You can test the middleware, such as http://localhost:19219/?culture=zh-CN, by passing Culture
The following code moves the middleware delegate to a class:
Using Microsoft.AspNetCore.Http;using System.Globalization;using System.Threading.Tasks;namespace Culture {public class RequestCultureMiddleware {private readonly RequestDelegate _ next; public RequestCultureMiddleware (RequestDelegate next) {_ next = next;} public Task Invoke (HttpContext context) {var cultureQuery = context.Request.Query ["culture"] If (! string.IsNullOrWhiteSpace (cultureQuery)) {var culture = new CultureInfo (cultureQuery); CultureInfo.CurrentCulture = culture; CultureInfo.CurrentUICulture = culture;} / / Call the next delegate/middleware in the pipeline return this._next (context);}
The following middleware is exposed through the extension method of IApplicationBuilder:
Using Microsoft.AspNetCore.Builder;namespace Culture {public static class RequestCultureMiddlewareExtensions {public static IApplicationBuilder UseRequestCulture (this IApplicationBuilder builder) {return builder.UseMiddleware ();}
The following code calls the middleware from Configure:
Public class Startup {public void Configure (IApplicationBuilder app) {app.UseRequestCulture (); app.Run (async (context) = > {await context.Response.WriteAsync ($"Hello {CultureInfo.CurrentCulture.DisplayName}");});}}
Middleware should follow the principle of explicit dependency by exposing its dependency in its constructor. Middleware is built once in the application life cycle. If you need to share services with middleware in the request, see the request correlation below.
Middleware components can resolve the dependency of dependency injection by constructing method parameters. UseMiddleware can also accept other parameters directly.
Dependencies for each request
Because the middleware is built at application startup rather than each request, the scope lifecycle services used by the middleware constructor are not shared with other dependency injection types during each request. If you must share scope services between middleware and other types, add them to the signature of the Invoke method. The Invoke method can accept other parameters populated by dependency injection. For example:
Public class MyMiddleware {private readonly RequestDelegate _ next; public MyMiddleware (RequestDelegate next) {_ next = next;} public async Task Invoke (HttpContext httpContext, IMyScopedService svc) {svc.MyProperty = 1000; await _ next (httpContext);}} "what is ASP.NET Core middleware Middleware" ends here, thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.