What is the use of "Map" extension while adding middleware to C# ASP.NET Core pipeline?

The Map extension method in ASP.NET Core is used for conditional middleware execution based on the request path. It allows you to branch the middleware pipeline and execute different middleware components for specific URL paths, creating a more organized and efficient request handling system.

Middleware components are assembled into an application pipeline to handle requests and responses. Each component can choose whether to pass the request to the next component and perform actions before and after the next component is invoked.

Syntax

Following is the syntax for using the Map extension method −

app.Map("/path", appBuilder => {
    // Configure middleware for this specific path
});

Following is the syntax for using the MapWhen extension method with predicates −

app.MapWhen(context => condition, appBuilder => {
    // Configure middleware based on custom condition
});

How Map Extensions Work

The Map extension method matches request delegates based on a request's path. When a request matches the specified path, the pipeline branches to execute the configured middleware. If the path doesn't match, the request continues down the main pipeline.

Middleware Pipeline Branching with Map Request Path Check Match No Match Mapped Pipeline Main Pipeline

Using Map for Path-Based Branching

Example

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;

public class Startup {
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
        app.Map("/maptest", HandleMapTest);
        
        app.Run(async context => {
            await context.Response.WriteAsync("Main pipeline - Hello World!");
        });
    }
    
    private static void HandleMapTest(IApplicationBuilder app) {
        app.Run(async context => {
            await context.Response.WriteAsync("Map Test Successful - This is the mapped pipeline!");
        });
    }
}

public class Program {
    public static void Main(string[] args) {
        var builder = WebApplication.CreateBuilder(args);
        var app = builder.Build();
        
        var startup = new Startup();
        startup.Configure(app, app.Environment);
        
        app.Run();
    }
}

In this example, requests to /maptest will be handled by the HandleMapTest method, while all other requests continue through the main pipeline.

Using MapWhen for Conditional Branching

Example

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;

public class Startup {
    private readonly IWebHostEnvironment _environment;
    
    public Startup(IWebHostEnvironment environment) {
        _environment = environment;
    }
    
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
        app.MapWhen(context => {
            return context.Request.Query.ContainsKey("branch");
        }, HandleBranch);
        
        app.Run(async context => {
            await context.Response.WriteAsync("Hello from " + _environment.EnvironmentName);
        });
    }
    
    private static void HandleBranch(IApplicationBuilder app) {
        app.Run(async context => {
            await context.Response.WriteAsync("Branch used - Custom condition matched!");
        });
    }
}

public class Program {
    public static void Main(string[] args) {
        var builder = WebApplication.CreateBuilder(args);
        var app = builder.Build();
        
        var startup = new Startup(app.Environment);
        startup.Configure(app, app.Environment);
        
        app.Run();
    }
}

The MapWhen method uses a predicate of type Func<HttpContext, bool> to determine when to branch. In this example, requests with a "branch" query parameter will be handled by the branched pipeline.

Nested Map Usage

Example

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;

public class Program {
    public static void Main(string[] args) {
        var builder = WebApplication.CreateBuilder(args);
        var app = builder.Build();
        
        app.Map("/level1", level1App => {
            level1App.Map("/level2a", level2AApp => {
                level2AApp.Run(async context => {
                    await context.Response.WriteAsync("Nested path: /level1/level2a");
                });
            });
            
            level1App.Map("/level2b", level2BApp => {
                level2BApp.Run(async context => {
                    await context.Response.WriteAsync("Nested path: /level1/level2b");
                });
            });
            
            level1App.Run(async context => {
                await context.Response.WriteAsync("Level 1 path: /level1");
            });
        });
        
        app.Run(async context => {
            await context.Response.WriteAsync("Root path - Main pipeline");
        });
        
        app.Run();
    }
}

Maps can be nested to create hierarchical routing structures. The above example handles /level1, /level1/level2a, and /level1/level2b paths with different middleware pipelines.

Common Use Cases

  • API Versioning: Route different API versions to separate middleware pipelines.

  • Admin Areas: Apply special authentication and authorization middleware to admin sections.

  • Feature Toggles: Use MapWhen to enable features based on user roles or configuration settings.

  • Legacy System Integration: Route specific paths to different middleware stacks for backward compatibility.

Conclusion

The Map extension methods in ASP.NET Core provide powerful pipeline branching capabilities based on request paths or custom conditions. They enable clean separation of concerns by allowing different middleware configurations for specific routes, making applications more modular and maintainable.

Updated on: 2026-03-17T07:04:36+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements