Understanding middleware in ASP.NET Core

In anticipation of the "C # ASP.NET Core developer" course , we invite you to sign up for an open lesson on the topic "Logging and tracing requests in asp.net core" .



In the meantime, we are sharing with you a traditional useful translation.


Middleware ASP.NET Core. :

  • Middleware?

  • Middleware ?

  • Run, Use Map.

  • Middleware?

  • Middleware?

Middleware?

Middleware ( ) β€” , .

, middleware- , middleware- middleware- , JavaScript, CSS, . .

 Middleware .NET Core, NuGet . Middleware- onfigure (Startup). Configure ASP.NET Core . , .

  , middleware-.

, middleware middleware .

middleware- middleware . (short-circuiting) . , . , , CSS, JavaScript, . ., middleware- , .

  ASP.NET Core - middleware Configure Startup.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)    
{    
    if (env.IsDevelopment())    
    {    
        //This middleware is used reports app runtime errors in development environment.  
        app.UseDeveloperExceptionPage();    
    }    
    else    
    {    
        //This middleware is catches exceptions thrown in production environment.   
        app.UseExceptionHandler("/Error");   
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.    
        app.UseHsts(); //adds the Strict-Transport-Security header.    
    }    
    //This middleware is used to redirects HTTP requests to HTTPS.  
    app.UseHttpsRedirection();   
    
    //This middleware is used to returns static files and short-circuits further request processing.   
    app.UseStaticFiles();  
    
    //This middleware is used to route requests.   
    app.UseRouting();   
    
    //This middleware is used to authorizes a user to access secure resources.  
    app.UseAuthorization();    
    
    //This middleware is used to add Razor Pages endpoints to the request pipeline.    
    app.UseEndpoints(endpoints =>    
    {    
        endpoints.MapRazorPages();               
    });    
} 

ASP.NET Core middleware-, , Configure. Microsoft .

Middleware

Middleware- , , middleware , , . middleware , .

middleware- :

middleware- , ( ) middleware. middleware- , . - .

Run, Use Map

app.Run()

middleware- Run[Middleware], . , middleware , middleware-.

 app.Use()

  middleware. app.Run(), next, . () , next. 

  app.Use() app.Run() /:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)    
{    
    app.Use(async (context, next) =>    
    {    
        await context.Response.WriteAsync("Before Invoke from 1st app.Use()\n");    
        await next();    
        await context.Response.WriteAsync("After Invoke from 1st app.Use()\n");    
    });    
    
    app.Use(async (context, next) =>    
    {    
        await context.Response.WriteAsync("Before Invoke from 2nd app.Use()\n");    
        await next();    
        await context.Response.WriteAsync("After Invoke from 2nd app.Use()\n");    
    });    
    
    app.Run(async (context) =>    
    {    
        await context.Response.WriteAsync("Hello from 1st app.Run()\n");    
    });    
    
    // the following will never be executed    
    app.Run(async (context) =>    
    {    
        await context.Response.WriteAsync("Hello from 2nd app.Run()\n");    
    });    
}    

app.Run() . (Β«Hello from 1st app.Run()Β»), Run.

app.Map()

. Map . , .

app.Map() /:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
{  
    app.Map("/m1", HandleMapOne);  
    app.Map("/m2", appMap => {  
        appMap.Run(async context =>  
        {  
            await context.Response.WriteAsync("Hello from 2nd app.Map()");  
        });  
    });  
    app.Run(async (context) =>  
    {  
        await context.Response.WriteAsync("Hello from app.Run()");  
    });  
}  
private static void HandleMapOne(IApplicationBuilder app)  
{  
    app.Run(async context =>  
    {  
        await context.Response.WriteAsync("Hello from 1st app.Map()");  
    });   
}  

localhost .

Request

Response

https://localhost:44362/

Hello from app.Run()

https://localhost:44362/m1

Hello from 1st app.Map()

https://localhost:44362/m1/xyz

Hello from 1st app.Map()

https://localhost:44362/m2

Hello from 2nd app.Map()

https://localhost:44362/m500

Hello from app.Run()

Middleware

Middleware . Middleware InvokeAsync() RequestDelegate . RequestDelegate middleware .

, middleware URL- -.

public class LogURLMiddleware  
{  
    private readonly RequestDelegate _next;  
    private readonly ILogger<LogURLMiddleware> _logger;  
    public LogURLMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)  
    {  
        _next = next;  
        _logger = loggerFactory?.CreateLogger<LogURLMiddleware>() ??  
        throw new ArgumentNullException(nameof(loggerFactory));  
    }  
    public async Task InvokeAsync(HttpContext context)  
    {  
        _logger.LogInformation($"Request URL: {Microsoft.AspNetCore.Http.Extensions.UriHelper.GetDisplayUrl(context.Request)}");  
        await this._next(context);  
    }
}
public static class LogURLMiddlewareExtensions  
{  
    public static IApplicationBuilder UseLogUrl(this IApplicationBuilder app)  
    {  
        return app.UseMiddleware<LogURLMiddleware>();  
    }  
} 

Configure:

app.UseLogUrl(); 

Middleware

  - .

  .

  , wwwroot. Middleware UseDirectoryBrowser , .

app.UseDirectoryBrowser(new DirectoryBrowserOptions  
{  
    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images")),  
    RequestPath = "/images"  
}); 

 Middleware ASP.NET Core , HTTP-.

  , middleware- ASP.NET Core:

  • , .

  • middleware .

  • middleware .

  • () .

  • , .

, - ! !


.




All Articles