【问题标题】:Custom Error page | Redirect type =301?自定义错误页面 |重定向类型=301?
【发布时间】:2013-02-23 22:22:32
【问题描述】:

我想这可能是一个新手问题(我是谁 :))。 在将用户重定向到自定义错误页面时,例如404,表示没有找到该页面,这个重定向的类型是302。

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

是否可以通过 Web.config 进行此重定向 301?

在此先感谢各位代码狂人。

【问题讨论】:

  • 您应该小心 301,因为某些客户端会更新他们存储的链接。这可能意味着导致 404 的临时故障(可能是在手动发布期间?)将永久破坏他们的链接。来自 rfc2616 The requested resource has been assigned a new permanent URI and any future references to this resource SHOULD use one of the returned URIs. Clients with link editing capabilities ought to automatically re-link references to the Request-URI to one or more of the new references returned by the server, where possible. This response is cacheable unless indicated otherwise.

标签: asp.net .net web-config


【解决方案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();
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-08
    • 1970-01-01
    • 2017-10-27
    • 1970-01-01
    • 1970-01-01
    • 2014-05-06
    • 2014-07-23
    • 2022-10-12
    相关资源
    最近更新 更多