2009-09-02 79 views

回答

-1

您可以使用

Server.Transfer("404error.aspx") 
1

我使用HTTP模塊來處理這個問題。它適用於其他類型的錯誤,而不僅僅是404s,並允許您繼續使用自定義錯誤web.config部分來配置顯示哪個頁面。

public class CustomErrorsTransferModule : IHttpModule 
{ 
    public void Init(HttpApplication context) 
    { 
     context.Error += Application_Error; 
    } 

    public void Dispose() { } 

    private void Application_Error(object sender, EventArgs e) 
    { 
     var error = Server.GetLastError(); 
     var httpException = error as HttpException; 
     if (httpException == null) 
      return; 

     var section = ConfigurationManager.GetSection("system.web/customErrors") as CustomErrorsSection; 
     if (section == null) 
      return; 

     if (!AreCustomErrorsEnabledForCurrentRequest(section)) 
      return; 

     var statusCode = httpException.GetHttpCode(); 
     var customError = section.Errors[statusCode.ToString()]; 

     Response.Clear(); 
     Response.StatusCode = statusCode; 

     if (customError != null) 
      Server.Transfer(customError.Redirect); 
     else if (!string.IsNullOrEmpty(section.DefaultRedirect)) 
      Server.Transfer(section.DefaultRedirect); 
    } 

    private bool AreCustomErrorsEnabledForCurrentRequest(CustomErrorsSection section) 
    { 
     return section.Mode == CustomErrorsMode.On || 
       (section.Mode == CustomErrorsMode.RemoteOnly && !Context.Request.IsLocal); 
    } 

    private HttpResponse Response 
    { 
     get { return Context.Response; } 
    } 

    private HttpServerUtility Server 
    { 
     get { return Context.Server; } 
    } 

    private HttpContext Context 
    { 
     get { return HttpContext.Current; } 
    } 
} 

啓用你的web.config中相同的方式與任何其他模塊

<httpModules> 
    ... 
    <add name="CustomErrorsTransferModule" type="WebSite.CustomErrorsTransferModule, WebSite" /> 
    ... 
</httpModules> 
5

作爲一般ASP.NET溶液,在web.config中的customErrors部分,添加redirectMode = 「ResponseRewrite」屬性。

<customErrors mode="On" redirectMode="ResponseRewrite"> 
    <error statusCode="404" redirect="/404.aspx" /> 
</customErrors> 

注意:這在內部使用Server.Transfer(),因此重定向必須是Web服務器上的實際文件。它不能是一個MVC路線。

+0

注意這是3.5 SP1中添加的。 – 2014-03-06 17:11:17

+0

我有一個網頁拋出InvalidOperationException導致500錯誤被返回。但是,當我添加上面的配置代碼片段時,顯示錯誤頁面,但HTTP狀態代碼更改爲200.使用ASP.NET 4.0和4.5。 – bloudraak 2014-08-20 19:34:03

+1

是的解決方法是在404.aspx.cs中重寫的Render方法中手動設置Response.StatusCode。可能有更好的解決方案,但這似乎工作。 – warrickh 2014-08-21 00:10:10

相關問題