Home > Backend Development > C#.Net Tutorial > What is the use of the 'Map' extension when adding middleware to a C# ASP.NET Core pipeline?

What is the use of the 'Map' extension when adding middleware to a C# ASP.NET Core pipeline?

王林
Release: 2023-09-13 21:13:06
forward
1027 people have browsed it

向 C# ASP.NET Core 管道添加中间件时,“Map”扩展有什么用?

Middleware is a software component assembled into an application pipeline Handle requests and responses.

Each component chooses whether to pass the request to the next component pipeline and can perform certain operations before and after the next component Called in the pipeline.

Map extensions are used as conventions for pipeline branches.

Map extension method is used to match request delegates based on the requested delegate. path.Map simply accepts a path and a function to configure the individual middleware pipeline.

In the example below, any request with a base path of /maptest will be processed Through the pipeline configured in the HandleMapTest method.

Example

private static void HandleMapTest(IApplicationBuilder app){
   app.Run(async context =>{
      await context.Response.WriteAsync("Map Test Successful");
   });
}
public void ConfigureMapping(IApplicationBuilder app){
   app.Map("/maptest", HandleMapTest);
}
Copy after login

In addition to path-based mapping, the MapWhen method also supports predicate-based mapping.

Middleware forking that allows building separate pipelines with great flexibility fashion.

Any predicate of type Func can be used to map requests to New pipeline branch.

private static void HandleBranch(IApplicationBuilder app){
   app.Run(async context =>{
      await context.Response.WriteAsync("Branch used.");
   });
}
public void ConfigureMapWhen(IApplicationBuilder app){
   app.MapWhen(context => {
      return context.Request.Query.ContainsKey("branch");
   }, HandleBranch);
      app.Run(async context =>{
         await context.Response.WriteAsync("Hello from " + _environment);
   });
}
Copy after login

Map can also be nested

app.Map("/level1", level1App => {
   level1App.Map("/level2a", level2AApp => {
      // "/level1/level2a"
      //...
   });
   level1App.Map("/level2b", level2BApp => {
      // "/level1/level2b"
      //...
   });
});
Copy after login

The above is the detailed content of What is the use of the 'Map' extension when adding middleware to a C# ASP.NET Core pipeline?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template