首页 > 解决方案 > 在抛出 404 之前有没有办法避免 302 重定向?

问题描述

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

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

标签: asp.net-mvchttp-status-code-404

解决方案


What you're looking for is the attribute redirectMode="ResponseRewrite" on the customErrors tag of the web.config. Unfortunatly it only works with aspx, and doesn't work for ASP.NET MVC.

So to achieve what you want in MVC you have to handle the error to write the response that you want.

in 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);
        }
    }
}

this code will handle the 404 error, and call the action Error404 on the ErrorsController without doing a redirect.


推荐阅读