【发布时间】:2015-10-09 09:08:02
【问题描述】:
假设我有 hotfound.html 页面,我想在找不到页面(或 wab api 方法)时显示它。
如何在 OWIN 应用程序中处理它?
谢谢
【问题讨论】:
标签: .net http-status-code-404 asp.net-web-api owin katana
假设我有 hotfound.html 页面,我想在找不到页面(或 wab api 方法)时显示它。
如何在 OWIN 应用程序中处理它?
谢谢
【问题讨论】:
标签: .net http-status-code-404 asp.net-web-api owin katana
您可以制作一个 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);
【讨论】:
await Next.Invoke(context) 将导致错误在我调用重定向之前被传递回用户。