Middleware is used to configure the request pipeline to the web application to process the request and the corresponding.

We can configure request delegation through three extension methods Run, Map, and Use. You can specify a single request delegate as an anonymous inline method, or as a definition in a reusable class. These reusable classes or anonymous methods are called middleware.

Run

public class Startup
{
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.Run(async (context) =>
        {
            await context.Response.WriteAsync("Hello World!");
        });
    }
}

This is a code in Startup.cs, where app.Run responded to the request in the pipeline.

Use

Multiple middleware can be linked through app.Use and the next parameter can be used to control whether the request is to be delivered to the next middleware.

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.Use(async (context, next) =>
        {
            // Do work that doesn't write to the Response.
            await next.Invoke();
            // Do logging or other work that doesn't write to the Response.
        });

        app.Run(async context =>
        {
            await context.Response.WriteAsync("Hello from 2nd delegate.");
        });
    }
}

The order in which middleware is added to Configure defines the order in which it is called. It is critical to the security, performance and function of the application. Each middleware can decide not to pass the request to the next middleware before or after the operation.

public class Startup
{
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
    
        app.Run(async (context) =>
        {
            await context.Response.WriteAsync("Hello World!");
        });
    }
}

As above, judging from env.IsDevelopment() , it means adding app.UseDeveloperExceptionPage() Middleware in development mode to handle program exceptions. When an exception occurs, it will directly return the exception information and no longer pass the request down.

Map

If you need to request to specify the request path, you can configure the path based pipeline request through app.Map to expand the pipeline branch.

public class Startup
{
    private static void HandleMapTest1(IApplicationBuilder app)
    {
        app.Run(async context =>
        {
            await context.Response.WriteAsync("Map Test 1");
        });
    }

    private static void HandleMapTest2(IApplicationBuilder app)
    {
        app.Run(async context =>
        {
            await context.Response.WriteAsync("Map Test 2");
        });
    }

    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. <p>");
        });
    }
}

Using the above code, the following requests and responses are displayed:

localhost:1234 > Hello from non-Map delegate.
localhost:1234/map1 > Map Test 1
localhost:1234/map2 > Map Test 2
localhost:1234/map3 > Hello from non-Map delegate.

Map supports nesting, for example:

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

Map also supports multiple fields, such as:

app.Map("/level1/level2", HandleMultiSeg);

Built in middleware of ASP. Net core

  • Authentication: provides authentication support.
  • CORS: configure cross source resource sharing.
  • Response Caching: supports caching responses.
  • Response Compression: supports compression of responses.
  • Routing: define and constrain routing requests.
  • Session: provides support for managing user sessions.
  • Static files: support static file and directory browsing.
  • URL Rewriting Middleware: supports URL rewriting and redirection requests.

Developing Middleware

Develop a middleware to view the IP address of access request

public class Startup
{
    private readonly ILogger _logger;
    
    public Startup(ILoggerFactory loggerFactory)
    {
        _logger = loggerFactory.CreateLogger<Startup>();
    }

    public void Configure(IApplicationBuilder app)
    {
        app.Use((context, next) =>
        {
            _logger.LogInformation("IP: " + context.Connection.RemoteIpAddress.ToString());

            //Call next Middleware
            return next();
        });

        app.Run(async (context) =>
        {
           await context.Response.WriteAsync("Hello World!");
        });

    }
}

Middleware is usually encapsulated in a class and exposes an extension method, such as:

public class RequestIPMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger _logger;

    public RequestIPMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
    {
        _next = next;
        _logger = loggerFactory.CreateLogger<RequestIPMiddleware>();
    }

    public async Task Invoke(HttpContext context)
    {
        _logger.LogInformation("IP2: " + context.Connection.RemoteIpAddress.ToString());
        await _next.Invoke(context);
    }
}

public static class RequestIPMiddlewareExtensions
{
    public static IApplicationBuilder UseRequestIP(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<RequestIPMiddleware>();
    }
}

Called by the following code:

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseRequestIP();

        app.Run(async (context) =>
        {
           await context.Response.WriteAsync("Hello World!");
        });
    }
}

Other resources

ASP.NET Core Middleware Fundamentals

All Comments

Leave a Reply Cancel Reply

Tips: Your email address will not be disclosed!

If you can't see clearly,please click to change...

Popular Posts

Collections