Grundlegendes zur Middleware in ASP.NET Core

Im Vorgriff auf den Kurs "C # ASP.NET Core-Entwickler" laden wir Sie ein, sich für eine offene Lektion zum Thema "Protokollieren und Nachverfolgen von Anforderungen in asp.net core" anzumelden .



In der Zwischenzeit teilen wir Ihnen eine traditionelle nützliche Übersetzung mit.


Dieser Artikel behandelt die Konzepte der Middleware in ASP.NET Core. Am Ende dieses Artikels haben Sie ein klares Verständnis der folgenden Punkte:

  • Was ist Middleware?

  • Warum ist die Bestellung von Middleware wichtig?

  • Run-, Use- und Map-Methoden.

  • Wie erstelle ich meine eigene Middleware?

  • Wie implementiere ich das Durchsuchen von Verzeichnissen mit Middleware?

Was ist Middleware?

Middleware (Middleware oder Middleware) ist ein Code in der Pipeline einer Anwendung, mit dem Anforderungen und Antworten verarbeitet werden.

Beispielsweise können wir eine Middleware-Komponente für die Benutzerauthentifizierung, eine Middleware-Komponente für die Fehlerbehandlung und eine weitere Middleware-Komponente für die Bereitstellung statischer Dateien wie JavaScript-Dateien, CSS-Dateien, verschiedene Arten von Bildern usw. haben.

 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