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?

王林
王林forward
2023-09-13 21:13:061034browse

向 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);
}

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 Func2da37665db817b80d4559ae8a837d13a 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);
   });
}

Map can also be nested

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

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete