c# - 如何从 ASP.NET MVC 中的 404 Not Found 错误中删除查询字符串

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

我已经使用 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 重写?

最佳答案

如果我对你的理解是正确的,你想处理 404 Not Found 错误,无需重写 url 并通过简单地返回结果 View 来处理

实现此目的的一种方法是使用旧的 customErrors,但使用 redirectMode="ResponseRewrite" 以确保原始 url 未更改。

   <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 时才成功 without redirectMode="ResponseRewrite "

我的结论:您可能正在使用没有 ResponseRewritecustomErrors,它优先于 httpErrors 处理程序。

关于c# - 如何从 ASP.NET MVC 中的 404 Not Found 错误中删除查询字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29715487/

相关文章:

c# - Silverlight 控件类似于 VS 中的 C# 文本编辑器

c# - viewstate MAC 验证失败 - 查看状态错误

c# - 正确使用 asp.net webforms 生命周期

javascript - 如何从分层数据生成 Kendo Treeview ? AngularJS

C#.NET DirectShow 库 : Saving custom graph to a file

c# - 无法在用于过滤的数据表列的名称中包含破折号 (-)

asp.net - 在 ASP.NET 中存储记录锁定 token

css - 在 ASP.NET 中强制 Gridview 标题字体粗体为 false

.net - 从 Python 到 F# 的字符串替换实用程序转换

c# - C# (.NET 2.0) 中 Windows 的进程间通信