3

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

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

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

提前感谢你们所有的代码狂人。

4

1 回答 1

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();
        }
    }
于 2013-11-07T15:32:52.780 回答