Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the query string from 404 Not Found errors in ASP.NET MVC

I have set up a custom 404 Not Found error page using the httpErrors section in my Web.config file.

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

When I navigate to a non-existent page, I get the following URL:

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

I don't want the query string in the URL and I don't want to 301 or 302 redirect to the notfound page either. How can I achieve this? Using URL rewriting perhaps?

like image 819
Muhammad Rehan Saeed Avatar asked Apr 18 '15 09:04

Muhammad Rehan Saeed


1 Answers

If I understand you correctly, you want to handle 404 Not Found errors handled without re-writing the url and by simply returning a result view

One way to achieve this is to use the old customErrors but with redirectMode="ResponseRewrite" to ensure that the original url is not changed.

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

The other is to use the httpErrors method with existingResponse="Replace" Exactly the way you are currenly using it

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

I have tried to recreate your issue and only succeeded when I had both httpErrors and customErrors set without redirectMode="ResponseRewrite"

My Conclusion: you are probably using customErrors without ResponseRewrite which takes precedence over httpErrors handler.

like image 131
Dave Alperovich Avatar answered Nov 12 '22 14:11

Dave Alperovich