2013-03-08 75 views
3

我想這可能是一個新手問題(我是:))。 將用戶重定向到自定義錯誤頁面時,例如404,告訴頁面不存在,這個重定向的類型是302自定義錯誤頁面|重定向類型= 301?

<error statusCode="404" redirect="/Utility/Error404.aspx" /> 
    <error statusCode="400" redirect="/Utility/Error404.aspx" /> 

是否有可能使這種重定向301到Web.config文件?

在此先感謝你們所有的代碼瘋子。

+1

您應該小心301,因爲有些客戶端會更新他們存儲的鏈接。這可能意味着導致404(可能在手動發佈期間)的臨時故障將永久斷開它們的鏈接。來自rfc2616'所請求的資源已被分配一個新的永久URI,並且任何將來對這個資源的引用都應該使用返回的URI之一。在可能的情況下,具有鏈接編輯功能的客戶端應自動將對Request-URI的引用重新鏈接到服務器返回的一個或多個新引用。除非另有說明,否則此響應是可緩存的 – Basic 2013-03-08 21:09:14

回答

1

爲了避免這種情況,並用正確的HttpCode返回自定義視圖:

在你的web.config,刪除錯誤的元素和設置:

<system.webServer> 
    <httpErrors existingResponse="PassThrough" /> 
</system.webServer> 

在您的Global.asax,使用此呈現的自定義asp.net MVC視圖:

protected void Application_Error(object sender, EventArgs e) 
    { 
     var ex = HttpContext.Current.Server.GetLastError(); 
     if (ex == null) 
      return; 
     while (!(ex is HttpException)) 
      ex = ex.GetBaseException(); 
     var errorController = new ErrorsController(); 
     HttpContext.Current.Response.Clear(); 
     var httpException = (HttpException)ex; 
     var httpErrorCode = httpException.GetHttpCode(); 
     HttpContext.Current.Response.Write(errorController.GetErrorGeneratedView(httpErrorCode, new HttpContextWrapper(HttpContext.Current))); 
     HttpContext.Current.Response.End(); 
    } 

在您的自定義ErrorsController,添加此生成從asp.net的MVC查看HTML視圖:

public string GetErrorGeneratedView(int httpErrorCode, HttpContextBase httpContextWrapper) 
    { 
     var routeData = new RouteData(); 
     routeData.Values["controller"] = "Errors"; 
     routeData.Values["action"] = "Default"; 
     httpContextWrapper.Response.StatusCode = httpErrorCode; 
     var model = httpErrorCode; 
     using (var sw = new StringWriter()) 
     { 
      ControllerContext = new ControllerContext(httpContextWrapper, routeData, this); 
      var viewEngineResult = ViewEngines.Engines.FindPartialView(ControllerContext, "Default"); 
      ViewData.Model = model; 
      var viewContext = new ViewContext(ControllerContext, viewEngineResult.View, ViewData, TempData, sw); 
      viewEngineResult.View.Render(viewContext, sw); 
      return sw.ToString(); 
     } 
    }