Table of Contents
Example
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?

Sep 13, 2023 pm 09:13 PM

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

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 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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Leveraging C# for Scientific Computing and Data Analysis Leveraging C# for Scientific Computing and Data Analysis Aug 05, 2025 am 06:19 AM

C#canbeusedforscientificcomputinganddataanalysisbysettingupaproperenvironment,leveragingrelevantlibraries,andoptimizingperformance.First,installVisualStudioorVSCodewiththe.NETSDKasthefoundation.Next,useNuGetpackageslikeMath.NETNumericsforlinearalgebr

Optimizing C# Application Startup Time with ReadyToRun and AOT Compilation Optimizing C# Application Startup Time with ReadyToRun and AOT Compilation Aug 22, 2025 am 07:46 AM

ReadyToRun(R2R)improvesstartuptimebypre-compilingILtonativecodeduringpublish,reducingJITworkloadatruntime.2.NativeAOTcompilationeliminatestheJITentirelybycompilingtheentireapptonativecodeatbuildtime,enablingnear-instantstartup.3.UseR2Rforminimal-effo

Memory Management in .NET: Understanding Stack, Heap, and GC Memory Management in .NET: Understanding Stack, Heap, and GC Aug 27, 2025 am 06:25 AM

Thestackstoresvaluetypesandreferenceswithfast,automaticdeallocation;theheapholdsreferencetypeobjectsdynamically;andthegarbagecollectorreclaimsunreachableheapobjects.1.Thestackisthread-specific,limitedinsize,andstoreslocalvariables,methodparameters,an

Minimal APIs in ASP.NET Core 8: A Practical Deep Dive Minimal APIs in ASP.NET Core 8: A Practical Deep Dive Aug 22, 2025 pm 12:50 PM

MinimalAPIsin.NET8areaproduction-ready,high-performancealternativetocontrollers,idealformodernbackends.1.Structurereal-worldAPIsusingendpointgroupsandextensionmethodstokeepProgram.csclean.2.Leveragefulldependencyinjectionsupportbyinjectingservicesdir

Asynchronous Programming in C#: Common Pitfalls and Best Practices Asynchronous Programming in C#: Common Pitfalls and Best Practices Aug 08, 2025 am 07:38 AM

Alwaysuseasync/awaitallthewaydowninsteadofblockingwith.Resultor.Wait()topreventdeadlocksincontext-awareenvironments;2.Avoidmixingsynchronousandasynchronouscodebyensuringtheentirecallstackisasync;3.UseConfigureAwait(false)whentheoriginalcontextisn’tne

C# Dependency Injection: From Basics to Advanced Scenarios with DI Containers C# Dependency Injection: From Basics to Advanced Scenarios with DI Containers Aug 16, 2025 am 01:41 AM

DependencyInjection(DI)inC#isadesignpatternthatenablesloosecouplingbyinjectingdependenciesexternallyratherthancreatingtheminternally.1.DIpromotestestabilityandmaintainability,asseenwhenreplacingtightlycoupleddependencies(e.g.,newLogger())withconstruc

How to hash and salt a password in C#? How to hash and salt a password in C#? Aug 08, 2025 am 06:32 AM

TosecurelystorepasswordsinaC#application,youshouldhashthemwithasalt.1.UseRfc2898DeriveBytestoimplementPBKDF2,whichcombinesapassword,arandomsalt,andaniterationcounttogenerateasecurekey.2.Generatearandom16-bytesaltusingRandomNumberGenerator.3.UsePBKDF2

C# Source Generators: A Practical Guide to Metaprogramming C# Source Generators: A Practical Guide to Metaprogramming Aug 15, 2025 am 05:45 AM

SourceGenerators can automatically generate code at compile time, reducing duplicate code and improving performance; 1. It analyzes the syntax tree and generates new files during compilation by implementing the ISourceGenerator interface; 2. It cannot modify the original code, and can only add new types such as INotifyPropertyChanged implementation; 3. It needs to create independent project references and set Private=false to enable the generator; 4. The advantages are zero runtime overhead and strong type safety, and the disadvantages are difficult to debug and master RoslynAPI; this technology is suitable for scenarios such as automatic property notification, serialization, interface implementation, etc., and is an important tool for modern C# metaprogramming.

See all articles