IApplicationBuilder
登録済みのミドルウェアを使用する
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()
:ミドルウェアをカプセル化し、最後にUse
登録を使用します
//自定义中间件
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)
:
エンドポイント、パイプラインの最後にミドルウェアを追加すると、後続のミドルウェアは実行されなくなります
app.Run(async context => {
await context.Response.WriteAsync("hello world3");
});
Map()、MapWhen()
パイプラインにブランチを追加し、条件が一致する場合はブランチし、メインブランチに戻らないでください
Map()
:
app.Map(new PathString("/test"), application =>
{
application.Use(async (context, next) =>
{
await context.Response.WriteAsync("test");
await next();
});
});
MapWhen()
:条件付き実行、幅広であるMapWhen
よりもMap
処理範囲
app.MapWhen(context => context.Request.Path.Value.Contains("q"), application => {
application.Use(async (context, next) =>
{
await context.Response.WriteAsync("q");
await next();
});
});