LoginSignup
2
1

More than 5 years have passed since last update.

OWINミドルウェアの伝番制御について

Posted at

こんなミドルウェアがあったとして

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;しないと思わぬ結果になる恐れあり。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1