【问题标题】:404 error page in aps.net MVC maintaining the error urlaps.net MVC 中的 404 错误页面维护错误 url
【发布时间】:2021-06-26 22:13:19
【问题描述】:

我正在尝试在 asp.net 中创建 404 错误页面(不是 .net 核心,我没有 startup.cs 文件)

我已经在 webconfig 中使用了 .aspx,但是由于我必须使用 razor 模块,所以我不能继续这样做。

我的目标是保留错误的 url,以便我可以在 google 分析中捕获它。

当我在 webconfig 中的 customerrors 处使用 responseredirect 并将其指向 cshtml 视图时, 我在 url 上得到了“aspxerrorpath”,后面跟着错误的路径,但我希望 url 保持我输入的方式。

例如:http://localhost/error?aspxerrorpath=/adadasd

我想要的方式:http://localhost/adadasd

谁能帮帮我?

【问题讨论】:

    标签: c# asp.net asp.net-mvc model-view-controller


    【解决方案1】:

    我不相信您可以直接指向 cshtml 文件,因为它们是 MVC 管道的一部分,因此需要一个控制器。为了保持 URL 不变,您可以只使用 <customErrors mode="On" /> 并在 Global.asax Application_Error 方法中处理错误,您可以在其中 Server.Transfer 到错误控制器路由,您可以在其中呈现 cshtml 视图。

    全球.asax

    protected void Application_Error(object sender, EventArgs e)
    {
        var exception = Server.GetLastError();
        
        // Default error code in case we have nothing more specific to work with
        int errorStatusCode = 500;
        
        if (exception is HttpException httpException)
        {
            errorStatusCode = httpException.GetHttpCode();
        }
        
        // Rewrite the request URL to invoke the ErrorController
        Response.TrySkipIisCustomErrors = true;
        Response.Clear();
        Server.ClearError();
        
        Server.TransferRequest("~/error/" + errorStatusCode, false);
    }
    

    错误控制器操作:

    [Route("{statusCode}")]
    public ActionResult Index(int statusCode)
    {
        if (statusCode <= 0)
        {
            statusCode = 404;
        }
    
        Response.StatusCode = statusCode;
    
        return View(statusCode);
    }
    

    【讨论】:

      猜你喜欢
      • 2014-05-15
      • 2021-09-06
      • 2012-12-03
      • 2021-11-03
      • 1970-01-01
      • 1970-01-01
      • 2015-05-06
      • 1970-01-01
      • 2013-08-13
      相关资源
      最近更新 更多