【问题标题】:Is there anyway to avoid 302 redirect before throwing 404?在抛出 404 之前有没有办法避免 302 重定向?
【发布时间】:2018-11-13 16:45:53
【问题描述】:

在 MVC 中,在 statusCode 404 上定义了 customErrors 路径,该路径按预期工作,但在 404 之前返回状态代码 302。

我们可以避免这种临时重定向吗?

【问题讨论】:

    标签: asp.net-mvc http-status-code-404


    【解决方案1】:

    您正在寻找的是 web.config 的 customErrors 标记上的属性 redirectMode="ResponseRewrite"。不幸的是,它只适用于 aspx,不适用于 ASP.NET MVC。

    所以要在 MVC 中实现你想要的,你必须处理错误来编写你想要的响应。

    在 Global.asax.cs 中:

    protected void Application_Error(object sender, EventArgs e)
    {
        HttpException httpException = Server.GetLastError().GetBaseException() as HttpException;
    
        if (httpException != null)
        {
            if (httpException.GetHttpCode() == 404)
            {
                RouteData routeData = new RouteData();
                Response.Clear();
                Server.ClearError();
                routeData.Values.Add("controller", "Errors");
                routeData.Values.Add("action", "Error404");
                var requestContext = new RequestContext(new HttpContextWrapper(Context), routeData);
                var controller = ControllerBuilder.Current.GetControllerFactory().CreateController(requestContext, "Errors");
    
                controller.Execute(requestContext);
            }
        }
    }
    

    此代码将处理 404 错误,并在 ErrorsController 上调用操作 Error404 而不进行重定向。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-20
      • 2021-12-15
      • 2019-09-07
      • 1970-01-01
      • 2019-05-19
      • 2018-11-14
      • 1970-01-01
      • 2020-12-02
      相关资源
      最近更新 更多