2013-03-08 137 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(); 
     } 
    }