En prévision du cours "Développeur C # ASP.NET Core", nous vous invitons à vous inscrire à une leçon ouverte sur le thème "Journalisation et traçage des demandes dans asp.net core" .
En attendant, nous partageons avec vous une traduction traditionnelle utile.
Cet article présente les concepts du middleware ASP.NET Core. À la fin de cet article, vous aurez une compréhension claire des points suivants:
Qu'est-ce que le middleware?
Pourquoi l'ordre du middleware est-il important?
Méthodes Run, Use et Map.
Comment créer votre propre middleware?
Comment implémenter la navigation dans les répertoires à l'aide du middleware?
Qu'est-ce que le middleware?
L'intergiciel (middleware ou middleware) est un morceau de code dans le pipeline d'application utilisé pour traiter les demandes et les réponses.
Par exemple, nous pouvons avoir un composant middleware pour l'authentification des utilisateurs, un composant middleware pour la gestion des erreurs et un autre composant middleware pour servir des fichiers statiques tels que des fichiers JavaScript, des fichiers CSS, divers types d'images, etc.
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 .
() .
, .
, - ! !