OWIN middleware gets called more times than expect

2019-05-03 13:13发布

问题:

I am testing OWIN middleware and wrote the following middleware class. But strangely, I see that this middleware is called about four times in total when I request a URL without any path (localhost:<port>). However when I call localhost:<port>/welcome.htm or when I call localhost:<port>/default.htm it is only called once as expected. What am I missing?

public class MyMiddleware : OwinMiddleware
{
    public MyMiddleware(OwinMiddleware next)
        : base(next)
    {
    }

    public override async Task Invoke(IOwinContext context)
    {
        await this.Next.Invoke(context);

        if (context.Request.Path.HasValue && (context.Request.Path.Value == "/" || context.Request.Path.Value.EndsWith(".htm")))
        {
            using (var writer = new StreamWriter(context.Response.Body))
            {
                await writer.WriteLineAsync("Next middleware: " + this.Next.ToString());
            }
        }
    }
}

and here's my Startup configuration:

    public void Configuration(IAppBuilder appBuilder)
    {
        appBuilder.UseErrorPage(new ErrorPageOptions {
            ShowCookies = true,
            ShowEnvironment = true,
            ShowExceptionDetails = true,
            ShowHeaders = true,
            ShowQuery = true,
            ShowSourceCode = true,
            SourceCodeLineCount = 2
        });

        appBuilder.Use<MyMiddleware>();

        appBuilder.UseWelcomePage("/welcome.htm");
        appBuilder.UseStaticFiles();
    }
标签: iis owin katana