【问题标题】:How to remove the query string from 404 Not Found errors in ASP.NET MVC如何从 ASP.NET MVC 中的 404 Not Found 错误中删除查询字符串
【发布时间】:2015-06-25 06:23:12
【问题描述】:

我使用Web.config 文件中的httpErrors 部分设置了自定义404 Not Found 错误页面。

<httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404"/>
  <error statusCode="404" responseMode="ExecuteURL" path="/error/notfound"/>
</httpErrors>                                

当我导航到一个不存在的页面时,我得到以下 URL:

http://localhost/error/notfound?404;http://localhost/ThisPageDoesNotExist/

我不希望 URL 中的查询字符串,也不希望 301 或 302 重定向到未找到的页面。我怎样才能做到这一点?也许使用 URL 重写?

【问题讨论】:

  • 尝试将 responseMode 更改为 Redirect 而不是 ExecuteURL。
  • 这会导致重定向。我更喜欢 ExecuteURL 所做的重写。

标签: c# asp.net .net asp.net-mvc asp.net-mvc-5


【解决方案1】:

如果我对您的理解正确,您希望处理 404 Not Found 错误,而无需重写 url 并简单地返回结果视图

实现这一点的一种方法是使用旧的customErrors 但与redirectMode="ResponseRewrite" 一起使用,以确保不更改原始网址。

   <customErrors mode="On" redirectMode="ResponseRewrite">
    <error statusCode="404" redirect="~/NotFound" />
  </customErrors>  

另一种是将httpErrors 方法与existingResponse="Replace" 一起使用正是您当前使用它的方式

  <system.webServer>
    <httpErrors errorMode="Custom" existingResponse="Replace">
      <clear/>
      <error statusCode="404" path="/Errors/NotFound.html" responseMode="ExecuteURL"/>
    </httpErrors>
  </system.webServer>

我试图重现您的问题,但只有在我同时设置了 httpErrorscustomErrors 时才成功 没有 redirectMode="ResponseRewrite"

我的结论:您可能在使用 customErrors 而不使用 ResponseRewrite,它优先于 httpErrors 处理程序。

【讨论】:

    【解决方案2】:

    如果您在指定路径时提供自己的查询字符串,那么 .NET 将不会附加 aspxerrorpath

    例如:

    <customErrors mode="On" defaultRedirect="errorpage.aspx?error=1" >
    

    您还可以创建一个HttpHandler,它会捕获其中包含aspxerrorpath 的URL,并将其剥离。你也可以对 IIS7 中的重写模块做同样的事情。

    或者,在global.asax 中,捕获 404 错误并重定向到未找到文件页面。示例:

    void Application_Error(object sender, EventArgs e)
    {
        Exception ex = Server.GetLastError();
        if (ex is HttpException && ((HttpException)ex).GetHttpCode() == 404)
        {
            Response.Redirect("~/filenotfound.aspx");
        }
        else
        {
            // your global error handling here!
        }
    }
    

    【讨论】:

    • 那还是很丑。
    猜你喜欢
    • 2015-04-25
    • 1970-01-01
    • 2016-08-30
    • 2010-11-12
    • 2019-05-12
    • 2013-02-08
    • 2012-08-10
    • 2011-02-26
    • 2012-01-05
    相关资源
    最近更新 更多