如何在OWIN Katana中处理页面未找到错误?

时间:2015-07-20 09:39:47

标签: .net http-status-code-404 asp.net-web-api owin katana

假设我有hotfound.html页面,我想在找不到页面(或wab api方法)时显示它。

如何在OWIN应用程序中处理它?

由于

1 个答案:

答案 0 :(得分:6)

您可以制作一个OwinMiddleware来重定向NotFound响应(或任何其他响应)。

class NotFoundMiddleware : OwinMiddleware
{
    public NotFoundMiddleware(OwinMiddleware next, IAppBuilder app)
        : base(next)
    {
    }

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

        if (context.Response.StatusCode == 404)
        {
            context.Response.Redirect("notfound.html");
        }
    }
}

或直接在响应正文中返回html(即没有重定向)。

public override async Task Invoke(IOwinContext context)
    {
        await Next.Invoke(context);
        if (context.Response.StatusCode == 404)
        {
            using (StreamWriter writer = new StreamWriter(context.Response.Body))
            {
                string notFound = File.ReadAllText(@"Web\notfound.html");
                writer.Write(notFound);
                writer.Flush();
            }
        }
    }

请注意,您可能需要根据具体情况另外编辑响应,但这适用于我的简单Owin服务器。

在Startup.cs中,添加

 app.Use<NotFoundMiddleware>(app);