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

Muh*_*eed 5 .net c# asp.net asp.net-mvc asp.net-mvc-5

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

<httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404"/>
  <error statusCode="404" responseMode="ExecuteURL" path="/error/notfound"/>
</httpErrors>                                
Run Code Online (Sandbox Code Playgroud)

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

HTTP://本地主机/错误/ NOTFOUND 404; HTTP://本地主机/ ThisPageDoesNotExist /

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

Dav*_*ich 4

如果我理解正确的话,您想要处理404 Not Found 错误,而无需重写 url,只需返回结果视图即可

实现此目的的一种方法是使用旧的customErrorsbut withredirectMode="ResponseRewrite"以确保原始 url 不会更改。

   <customErrors mode="On" redirectMode="ResponseRewrite">
    <error statusCode="404" redirect="~/NotFound" />
  </customErrors>  
Run Code Online (Sandbox Code Playgroud)

httpErrors另一种方法是按照您当前使用的方式使用该方法existingResponse="Replace"

  <system.webServer>
    <httpErrors errorMode="Custom" existingResponse="Replace">
      <clear/>
      <error statusCode="404" path="/Errors/NotFound.html" responseMode="ExecuteURL"/>
    </httpErrors>
  </system.webServer>
Run Code Online (Sandbox Code Playgroud)

我试图重现你的问题,只有当我同时拥有这两个问题httpErrors并且没有customErrors设置时才成功 redirectMode="ResponseRewrite"

我的结论:您可能使用customErrorswithoutResponseRewrite优先于httpErrors处理程序。