假设我有hotfound.html页面,我想在找不到页面(或wab api方法)时显示它。
如何在OWIN应用程序中处理它?
由于
答案 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);