こんなミドルウェアがあったとして
public class HogeMiddleware : OwinMiddleware
{
public async override Task Invoke(IOwinContext context)
{
System.Diagnostics.Debug.WriteLine("Hoge Before");
await Next.Invoke(context);
System.Diagnostics.Debug.WriteLine("Hoge After");
}
}
public class FooMiddleware : OwinMiddleware
{
public async override Task Invoke(IOwinContext context)
{
System.Diagnostics.Debug.WriteLine("Foo Before");
await Next.Invoke(context);
System.Diagnostics.Debug.WriteLine("Foo After");
}
}
public class BarMiddleware : OwinMiddleware
{
public async override Task Invoke(IOwinContext context)
{
System.Diagnostics.Debug.WriteLine("Bar Before");
await Next.Invoke(context);
System.Diagnostics.Debug.WriteLine("Bar After");
}
}
StartupクラスでHogeMiddleware, FooMiddleware, BarMiddleware の順に登録し、アクセスした場合、
Hoge Before
Foo Before
Bar Before
Bar After
Foo After
Hoge After
と表示される。
Next.Invoke()呼び出したらそこで終わりではなく、それ以降に処理がある場合は、リクエスト時の処理とは逆順で事後処理が実行される。
ミドルウェアのInvokeメソッドで分岐が発生する場合は、分岐末尾でreturn;しないと思わぬ結果になる恐れあり。