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

I 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 go to a non-existent page, I get the following URL:

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

I don't need the query string in the url, and I don't want to redirect 301 or 302 to the notfound page. How can i achieve this? Is URL rewriting possible?

+5
source share
2 answers

If you understand correctly, you want to handle 404 Not Found errors, processed without re-writing the URL and just returning a representation of the result

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> 

Another is to use the httpErrors method with existingResponse="Replace" Just like you use it over time

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

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

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

+3
source

If you specify your own request when specifying the path, then .NET will not reference the aspxerrorpath .

For instance:

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

You can also create an HttpHandler that catches URLs with an aspxerrorpath in it and breaks it. You could probably do the same with the rewrite module in IIS7.

Or, in global.asax , catch a 404 error and redirect to a page not found in the file. Example:

 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! } } 
0
source

All Articles