Memahami middleware di ASP.NET Core

Untuk mengantisipasi kursus "C # ASP.NET Core developer", kami mengundang Anda untuk mendaftar ke pelajaran terbuka tentang topik "Pencatatan dan penelusuran permintaan di inti asp.net" .



Sementara itu, kami membagikan kepada Anda terjemahan tradisional yang berguna.


Artikel ini memperkenalkan konsep ASP.NET Core Middleware. Di akhir artikel ini, Anda akan memiliki pemahaman yang jelas tentang poin-poin berikut:

  • Apa itu Middleware?

  • Mengapa urutan Middleware penting?

  • Jalankan, Gunakan, dan metode Peta.

  • Bagaimana cara membuat Middleware Anda sendiri?

  • Bagaimana cara menerapkan penjelajahan direktori menggunakan Middleware?

Apa itu Middleware?

Middleware (middleware atau middleware) adalah potongan kode dalam pipeline aplikasi yang digunakan untuk memproses permintaan dan tanggapan.

Misalnya, kita dapat memiliki komponen middleware untuk otentikasi pengguna, komponen middleware untuk penanganan kesalahan, dan komponen middleware lainnya untuk menyajikan file statis seperti file JavaScript, file CSS, berbagai jenis gambar, dll.

 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