2011-10-04 129 views
5

你好我正在嘗試做一個重定向如果響應是一個404,但它沒有按預期工作,你可以專家看到這個問題?它還是到通用的404404自定義重定向

在我的Global.asax

protected void Application_BeginRequest(Object sender, EventArgs e) 
{ 
     if (Response.Status == "404 Not Found") 
     { 
      string notFound = "~/custom_notfound.aspx"; 
      Response.Redirect(notFound); 
     } 

} 

UPDATE

試過到目前爲止

(Response.Status == "404 Not Found") 
(Response.Status == "404") 
(Response.StatusCode == 404) 
+0

您的意思是把'的Response.Redirect(NOTFOUND);'? – Icarus

+0

PageNotFound是什麼? –

+0

ahh對不起,當張貼錯別字,但仍然有問題。謝謝 – user710502

回答

8

您還可以使用web.config中的customErrors部分 - as shown here

eg在system.web節,

<customErrors mode="On" defaultRedirect="/custom_error.aspx"> 
    <error statusCode="404" redirect="/custom_notfound.aspx" /> 
</customErrors> 
2

你可以添加到您的web.config中要做到這一點重定向,你不需要使用Application_BeginRequest來處理這個問題。

看到這個ServerFault question

如果您不能使用web.config,那麼我會將您的啓動頁面設置爲不存在的頁面,在您的BeginRequest中放置一個斷點,調試應用程序並查看請求以瞭解如何確定它是404.這將更容易確定最佳解決方案。

仔細研究一下,在HttpWebResponse類中使用了HttpStatusCode。因此,使用不同的應用程序覆蓋來獲取默認響應是有意義的,然後根據Enum檢查它的狀態。

+0

在任何情況下,出於某種原因,他們希望它在asax中完成,這將是在那裏做的方式? – user710502

3

我不認爲BeginRequest可能知道大約404錯誤。請嘗試實施Application_Error。檢查Server.GetLastError()是否是HttpException,如果是,請檢查狀態。

0

您還可以使用在web.config

<system.webServer> 
    <httpErrors errorMode="Custom" defaultResponseMode="File" > 
    <remove statusCode="404" /> 
    <remove statusCode="500" /> 
    <error statusCode="404" path="404.html" /> 
    <error statusCode="500" path="500.html" /> 
    </httpErrors> 
</system.webServer>