Reputation: 25151
Ive noticed that when I request a page in ASP.NET (webforms) that does not exist, the 'StaticFile' handler deals with the error notification.
Id like to be a bit more helpful in these situations.
What is the correct way for me to intercept this 404, and as a result, run some code to redirect the user?
Two ways Ive thought of doing which I currently don't really like are:
1 - Create a module that basically does a if (!file.exists($url){redirect to $correctedurl})
2 - Modify the error.aspx.cs(or the default error page) to do something similar (yuck!)
Upvotes: 0
Views: 971
Reputation: 6916
Create a HttpModule
that responds to the Error
-event of your application. In here you can get access the Exception
and StatusCode
of the Response and if the Code is 404 (NotFound) you can respons accordingly to it. Usually rewriting the request, setting StatusCode to Found and clearing the Exception
. That way customErrors in web.config wont be hit and the process will be $RequestedUrl -> $CorrectedURL.
This is an example of creating a HttpModule that responds to error events in asp.net.
http://www.codeproject.com/KB/aspnet/GlobalErrorHandler.aspx
Upvotes: 0
Reputation: 47387
Just rock the CustomErrors in the web.Config
<configuration>
<system.web>
<customErrors defaultRedirect="Error.htm"
mode="RemoteOnly">
<error statusCode="404"
redirect="~/NotFound.aspx"/>
</customErrors>
</system.web>
</configuration>
Upvotes: 0
Reputation: 16018
There are two areas that you have to modify in order to capture 404s. The first is in IIS itself, which will take care of any non-aspx files such as css, jpg, js, etc. The second is in the web.config of the app itself which will handle missing aspx's.
The link below shows how to accomplish this.
see here
Upvotes: 1
Reputation: 57179
The web config has a customErrors section that lets you specify where to direct specific error codes.
If you would like to intercept the request when it is first made you will need a Global.asax and respond to the BeginRequest event. At that point you can determine if a file exist on the server and Response.Redirect on the context. Just make sure you understand every request goes through that event including JS files, CSS and images. HttpApplication Documentation
Upvotes: 1