2015-07-20 56 views

回答

5

,您可以撥打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); 
+0

哦,太好了,謝謝,這工作。有沒有辦法顯示未找到頁面沒有重定向?即不要更改瀏覽器中的網址? – Burjua

+0

您可能希望以相同的方式攔截404狀態,但不是重定向,而是修改響應主體以包含一些基本的html(未找到的頁面)。如果您查看www.google.com/foo的回覆,這是他們如何顯示他們的404頁面。 – Zephyr

+0

好吧,知道我可以修改響應正文來返回文本響應,但是在這裏沒有辦法返回html文件嗎? – Burjua