Usar IApplicationBuilder
middleware registrado
Use()
:
app.Use(async (context, next) =>
{
await context.Response.WriteAsync("hello world");
await next.Invoke();
});
app.Use((requestDelegate) =>
{
return async (context) =>
{
await context.Response.WriteAsync("hello world2");
await requestDelegate(context);
};
});
UseMiddleWare()
: Encapsula el middleware y finalmente usa el Use
registro.
//自定义中间件
public class TestMiddelware
{
public RequestDelegate _next;
public TestMiddelware(RequestDelegate next)
{
this._next = next;
}
public Task Invoke(HttpContext context)
{
if (context.Request.Path.Value.Contains("1.jpg"))
{
return context.Response.SendFileAsync("1.jpg");
}
if (this._next != null)
{
return this._next(context);
}
throw new Exception("TestMiddelware error");
}
}
app.UseMiddleware<TestMiddelware>(app, Array.Empty<object>());
Run(RequestDelegate handler)
:
Punto final, agregue un middleware al final de la canalización y el middleware posterior ya no se ejecutará
app.Run(async context => {
await context.Response.WriteAsync("hello world3");
});
Map()、MapWhen()
Agregue ramas a la tubería, bifurque si la condición coincide y no vuelva a la rama principal
Map()
:
app.Map(new PathString("/test"), application =>
{
application.Use(async (context, next) =>
{
await context.Response.WriteAsync("test");
await next();
});
});
MapWhen()
: Ejecutar condicionalmente, que es más amplio MapWhen
que el Map
rango de procesamiento
app.MapWhen(context => context.Request.Path.Value.Contains("q"), application => {
application.Use(async (context, next) =>
{
await context.Response.WriteAsync("q");
await next();
});
});