Since ASP.NET does not implement the customError pages properly for 404 errors, I want to implement a custom error handling module to take its place. There are numerous examples on the Internet what needs to be in the code, but very little on how to implement
it.
After implementing the following code, when I navigate to a page that does not exist, I get a standard 404 error from IIS. I do not think my handler is working or I should see my custom 404 error page.
I am using Visual Studio Team System 2008 within Windows Vista SP1. The target is .NET 3.5, and I am using IIS to debug my projects, running VS as administrator to accomplish this.
Public Class HttpErrorModule
Implements IHttpModule
Public Sub Dispose() Implements System.Web.IHttpModule.Dispose
'Nothing to dispose.
End Sub
Public Sub Init(ByVal context As System.Web.HttpApplication) Implements System.Web.IHttpModule.Init
AddHandler context.Error, New EventHandler(AddressOf Context_Error)
End Sub
Private Sub Context_Error(ByVal sender As Object, ByVal e As EventArgs)
Dim context As HttpContext = CType(sender, HttpApplication).Context
If (context.Error.GetType Is GetType(HttpException)) Then
' Get the Web application configuration.
Dim configuration As System.Configuration.Configuration = WebConfigurationManager.OpenWebConfiguration("~/web.config")
' Get the section.
Dim customErrorsSection As CustomErrorsSection = CType(configuration.GetSection("system.web/customErrors"), CustomErrorsSection)
' Get the collection
Dim customErrorsCollection As CustomErrorCollection = customErrorsSection.Errors
Dim statusCode As Integer = CType(context.Error, HttpException).GetHttpCode
'Clears existing response headers and sets the desired ones.
context.Response.ClearHeaders()
context.Response.StatusCode = statusCode
If (customErrorsCollection.Item(statusCode.ToString) IsNot Nothing) Then
context.Server.Transfer(customErrorsCollection.Get(statusCode.ToString).Redirect)
Else
context.Response.Flush()
End If
End If
End Sub
End Class
I think, you might have misinterpretted the httpContext.Response.StatusCode. As far as I'm aware in .NET there is in fact no way you can programatically catch the HttpStatusCode of your error unless you create a function that evaluates the Exception.Message
for certain words or by some other evaluating means. The Response.StatusCode is most likely returning '200' better known as 'Everything is fine continue what you're doing'. I noticed this today as I was Error debugging today using a similar http module and
was surprised to find 200 returned. This is probably the reason why when your doing the server transfer its not directing you to your chosen error page. Why does it return 200 and not 404? I'm not entirely sure myself but I'd create a breakpoint at that
bit of code and evaluate it for yourself.
I don't know about you but for me, Progamming just ain't Programming with out brackets and braces. (loosely translated as I dislike VB)
I set my breakpoint within the init sub, and it did not get hit when debugging so I have not had a chance to debug the other parts. Am I not loading it correctly from web.config?
As for its ability to programatically catch an error, it was posted on a SEO site by a well known author. He posted the source code and has also published a DLL (which I can't seem to get to work either). My assumption is that the code is correct as other
people have left feedback thanking him as it works in their project. So far no response from the question I left on his page.
I am trying to understand your question here. Does it mean you don't want user to see the asp.net generated code rather you want them to see a customErrorPage? If so, this is how I handled this problem:
I created ErrorPage.aspx and added the following line in the web.config file.
Unfortunately I'm not best suited to VB.NET I'm afraid, so I couldn't tell off hand whether the code was right or wrong. but I am interested if .NET is able to pick up on the status error code. Could you possibly post the URL of the article from which you
sourced the code for me and maybe I could try it out tomorrow for myself after I've interpreted it in to c#. The web.config code looks alright to me, you've not namespaced any of it, so by all rights if you've cut and paste it word for word it should work
but hey, these things happen. If I find anything more I'll let you know. Sorry I couldn't be much help.
I don't know about you but for me, Progamming just ain't Programming with out brackets and braces. (loosely translated as I dislike VB)
If a user browses to a page that does not exist, the correct error page loads.
The problem, and it is a big problem, is that when the non existent page is accessed, IIS and .NET send out a 302 status code, that the resource has moved, and then loads the custom 404 page with IIS and .NET sending out a 200 status code.
No where does it send out a 404 status code. Bad, Bad, Bad for SEO.
This can be verified by running Fiddler, or any other packet analytic software.
I have modified my 404PageNotFound.aspx to include:
Response.ClearHeaders()
Response.StatusCode = 404
But that does not do the trick either.
Bottom line is I want to get my iHTTPModule to work, and I can't seem to verify if it is even loading properly to intercept requests.
well, now I am convinced it is not even listening to requests.
I added the following line to init
Public Sub Init(ByVal context As System.Web.HttpApplication) Implements System.Web.IHttpModule.Init Throw New HttpException("Exception Occured")
AddHandler context.Error, New EventHandler(AddressOf Context_Error)
End Sub
When I start the debugger, it just loads the home page of the project and does not throw the error leading me to believe it is not hooked incoming requests.
Thinking HttpErrorModule is a potential reserved word, I renamed my class and .vb file to myHttpErrorModule
Thought I'd forgotten about you didn't you? I've tried out the c# version of this code today and I have to admit I like it, and it works better then my previous version, so might just have to update a site or two now. Wish I'd heard of this sooner.
The only problem I encountered using the c# version was that a current site I'm building that uses UrlReWriting.NET wouldn't Server.Transfer to non-existent pages which meant I had to use Response.Redirect instead - which I wasn't too bothered about considering
I had no use for passing the error to the transferred page anyway. I suspect though this isn't your problem as your not using url rewrites, but you might want to try alterign the server.transfer method to use response.redirect. If you really need to use
the error information in the transferred page then look at storing it in context via session or something.
I did namespace the HttpErrorModule code and alter the web.config to suit so my web.config looked like
Note that I altered the type and removed the module type information after the comma. This works fine with my application.
Your customErrors information in your web.config looks fine to me, but just keep mode='On' to make sure your seeing the correct page just in case it is working else you won't know -of course don't mean to patronise.
also add 'Imports System' - just in case (I'm comparing my code to yours here)
Next if it's still not working, post all the information in the Exception error. Copy it all to clip board and post it up here.
Hope any of this helps.
Regards,
Luke
I don't know about you but for me, Progamming just ain't Programming with out brackets and braces. (loosely translated as I dislike VB)
can you post the top 10 lines or so of your file so I can see
what you are importing
your namespace
class name
physical name of your file?
Are you storing this in your App_Code folder?
I added "Imports System"
I am not getting an exception error. In fact, I think the whole thing is being ignored. I set a break point inside init and it did not even get hit.
I am running VS Team System 2008, 3.5 target, debugging within Vista's IIS 7
If I turn mode="On", I see the correct error page, but it is not going through the handler. What that means is my module is not being hit, and the ASP.NET implementation of error trapping returns a 302 code followed by a
200 code. Clearly Microsoft needs to fix this, which is why I am needing to implement this asap.
I am not going to be doing URL re-writing (at least not yet), so I am ok with the Server.Transfer method
Answer to 1. Posted the entire HttpModule (File-Name: CustomErrorModule.cs )
using System.Web; //Same as Imports
using System.Web.Configuration;
using System;
namespace LJ.Store.BLL.CustomErrors
{
public class HttpErrorModule : IHttpModule // the ':' denotes the inheritence
{
private void Context_Error(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
if ((object.ReferenceEquals(context.Error.GetType(), typeof(HttpException))))
{
// Get the Web application configuration.
System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~/web.config");
// Get the section.
CustomErrorsSection customErrorsSection = (CustomErrorsSection)configuration.GetSection("system.web/customErrors");
// Get the collection
CustomErrorCollection customErrorsCollection = customErrorsSection.Errors;
int statusCode = ((HttpException)context.Error).GetHttpCode();
//Clears existing response headers and sets the desired ones.
context.Response.ClearHeaders();
context.Response.StatusCode = statusCode;
if ((customErrorsCollection.Get(statusCode.ToString()) != null))
{
context.Response.Redirect(customErrorsCollection.Get(statusCode.ToString()).Redirect);
//context.Server.Transfer(customErrorsCollection.Get(statusCode.ToString()).Redirect, false);
}
else
{
context.Response.Flush();
}
}
}
#region IHttpModule Members
public void Dispose()
{
//Do nothing here
}
public void Init(HttpApplication context)
{
context.Error += new EventHandler(Context_Error);
}
#endregion
}
}
Answer to 2. Yes I am storing this in my App_Code Folder. It's a folder or two deep but you probably know that folder structure in your App_Code folder means nothing as the directory is compiled as if no folders exist anyway. I do it as it just makes things easier to find that's all.
Answer to 4. That is just bizarre.
Answer to 6. Actually I was reading up on this implementation of Custom Errors and apparently this was designed intentionally and they have no plans to change it.
Copy and Paste the Web.Config information as well for you.
If I go in IIS 7 and set the site to run under the Classic "Managed Pipeline Mode", it works as I thought it should. If I run it under the
Integrated "Managed Pipeline Mode", it does not.
I finally figured it out. Thank you so much for all of your help.
Evidently, IIS 7 in Vista / 2008 uses a new Managed Pipeline (which MS seems to assume everyone knows about)
What helped narrow it down is when I ran the site in IIS under Classic mode instead of Integrated mode. Since it finally worked in Classic mode, I could tell my module was not being called by IIS 7 from web.config.
I made the changes to my web.config to something along the lines of:
HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.
Module IIS Web Core
Notification BeginRequest
Handler Not yet determined
Error Code 0x800700b7
Config Error Cannot add duplicate collection entry of type 'add' with unique key attribute 'name' set to 'CustomErrorModule'
Config File \\?\C:\inetpub\wwwroot\web.config
so it is possible CustomErrorModule is a reserved key word in IIS 7, or perhaps it is just stuck in my GAC somewhere.
Regardless, I changed the filename from CustomErrorModule.vb to myCustomErrorModule.vb, renamed the class name within the file, and then modified web.config to show:
Running the code through my VS debugger, I am able to hit break points in init and in Context_Error when I click on a bad url. Right before the redirect occurs, I look at the immediate window and ensure the status code is 404, which is is. Great! everything
is working!
WRONG
If I run it outside of the debugger, it does not work
I rebuilt the solution, opened up IE, browsed to localhost, clicked on a bad link, and I still get the 302 to 200 redirect default ASP.NET redirect to my custom 404 page.
Checking further, I wanted to see how the module was loading outside the debugger.
To test, I modified init to
Public Sub Init(ByVal context As HttpApplication) Implements System.Web.IHttpModule.Init Throw New HttpException("Exception Occured")
AddHandler context.[Error], AddressOf Context_Error
End Sub
When I opened IE, and tried to load the page, I got a nice fat error, of which I was expecting.
I move "Throw New HttpException("Exception Occured")" from init to the first line inside Context_Error, and then click on a bad link, nothing happens!
WTH?
How do I get my handler to override the built in asp.net error redirect?
and, even bigger, why am I able to trap the error in the debugger, and simulate exactly how I want it to work, but the live version does not emulate the same response?
The above module maps to the <httpErrors /> configuration section that allows you to define your own custom paths to errors and exceptions that might occur in your applicaiton.
So I believe the main reason for what was happening is that, you defined a module that has been already defined for you with the same name.
Either you remove the original module (which I don't recommend) through the <remove name="CustomErrorModule" /> element or simply use a different Name for the module you are registering!
The above module maps to the <httpErrors /> configuration section that allows you to define your own custom paths to errors and exceptions that might occur in your applicaiton.
So I believe the main reason for what was happening is that, you defined a module that has been already defined for you with the same name.
Either you remove the original module (which I don't recommend) through the <remove name="CustomErrorModule" /> element or simply use a different Name for the module you are registering!
This is something I've been chasing for quite some time now - the ability for asp.net to produce a 404 response code, and redirect to a friendly page.
I've replicated your code (I was previously doing something similar in global.asax.cs); problem I've got is that when you put an event hander on context.Error, the Application_OnAuthenticateRequest hasn't fired - so you don't have a session (context.Session
= null). If I do a Server.Transfer, it goes to a friendly error page which inherits from a Master page that contains some basic functionality that reads the session, and it bombs out.
There *is* a session at this stage, I don't suppose you know of an alternative way of picking it up?
Member
20 Points
25 Posts
Custom 404 Error via iHTTPHandlerModule and EventHandler
Jun 10, 2008 03:07 PM|kapcreations|LINK
Since ASP.NET does not implement the customError pages properly for 404 errors, I want to implement a custom error handling module to take its place. There are numerous examples on the Internet what needs to be in the code, but very little on how to implement it.
After implementing the following code, when I navigate to a page that does not exist, I get a standard 404 error from IIS. I do not think my handler is working or I should see my custom 404 error page.
I am using Visual Studio Team System 2008 within Windows Vista SP1. The target is .NET 3.5, and I am using IIS to debug my projects, running VS as administrator to accomplish this.
I have created an entry in my web.config file as
<system.web>
<httpModules>
<add name="HttpErrorModule" type="HttpErrorModule, HttpErrorModule" />
</httpModules>
</system.web>
I have tried turning errors Off, On, RemoteOnly and commenting out the entire section
<customErrors mode="Off" defaultRedirect="~/Error.aspx">
<error statusCode="403" redirect="~/403Forbidden.aspx" />
<error statusCode="404" redirect="~/404PageNotFound.aspx" />
</customErrors>
I have created HttpErrorModule.vb in the App_Code directory (code listed below)
Imports System.Web
Imports System.Web.Configuration
Public Class HttpErrorModule
Implements IHttpModule
Public Sub Dispose() Implements System.Web.IHttpModule.Dispose
'Nothing to dispose.
End Sub
Public Sub Init(ByVal context As System.Web.HttpApplication) Implements System.Web.IHttpModule.Init
AddHandler context.Error, New EventHandler(AddressOf Context_Error)
End Sub
Private Sub Context_Error(ByVal sender As Object, ByVal e As EventArgs)
Dim context As HttpContext = CType(sender, HttpApplication).Context
If (context.Error.GetType Is GetType(HttpException)) Then
' Get the Web application configuration.
Dim configuration As System.Configuration.Configuration = WebConfigurationManager.OpenWebConfiguration("~/web.config")
' Get the section.
Dim customErrorsSection As CustomErrorsSection = CType(configuration.GetSection("system.web/customErrors"), CustomErrorsSection)
' Get the collection
Dim customErrorsCollection As CustomErrorCollection = customErrorsSection.Errors
Dim statusCode As Integer = CType(context.Error, HttpException).GetHttpCode
'Clears existing response headers and sets the desired ones.
context.Response.ClearHeaders()
context.Response.StatusCode = statusCode
If (customErrorsCollection.Item(statusCode.ToString) IsNot Nothing) Then
context.Server.Transfer(customErrorsCollection.Get(statusCode.ToString).Redirect)
Else
context.Response.Flush()
End If
End If
End Sub
End Class
What am I missing?
404 error handler module httpmodule
Member
31 Points
17 Posts
Re: Custom 404 Error via iHTTPHandler
Jun 10, 2008 03:53 PM|LukeJones|LINK
kapcreations,
I think, you might have misinterpretted the httpContext.Response.StatusCode. As far as I'm aware in .NET there is in fact no way you can programatically catch the HttpStatusCode of your error unless you create a function that evaluates the Exception.Message for certain words or by some other evaluating means. The Response.StatusCode is most likely returning '200' better known as 'Everything is fine continue what you're doing'. I noticed this today as I was Error debugging today using a similar http module and was surprised to find 200 returned. This is probably the reason why when your doing the server transfer its not directing you to your chosen error page. Why does it return 200 and not 404? I'm not entirely sure myself but I'd create a breakpoint at that bit of code and evaluate it for yourself.
Member
20 Points
25 Posts
Re: Custom 404 Error via iHTTPHandler
Jun 10, 2008 04:04 PM|kapcreations|LINK
Thanks for the reply.
I set my breakpoint within the init sub, and it did not get hit when debugging so I have not had a chance to debug the other parts. Am I not loading it correctly from web.config?
As for its ability to programatically catch an error, it was posted on a SEO site by a well known author. He posted the source code and has also published a DLL (which I can't seem to get to work either). My assumption is that the code is correct as other people have left feedback thanking him as it works in their project. So far no response from the question I left on his page.
Member
20 Points
25 Posts
Re: Custom 404 Error via iHTTPHandler
Jun 10, 2008 04:23 PM|kapcreations|LINK
how should I go about seeing if it is loaded properly?
Member
262 Points
130 Posts
Re: Custom 404 Error via iHTTPHandler
Jun 10, 2008 04:23 PM|mominlhp|LINK
I created ErrorPage.aspx and added the following line in the web.config file.
web.config file:
<customErrors defaultRedirect="~/ErrorPage.aspx" mode="RemoteOnly" />
Please remember to click "Mark as Answer" if you get the answer.
Thanks
~AK
Member
31 Points
17 Posts
Re: Custom 404 Error via iHTTPHandler
Jun 10, 2008 04:26 PM|LukeJones|LINK
Unfortunately I'm not best suited to VB.NET I'm afraid, so I couldn't tell off hand whether the code was right or wrong. but I am interested if .NET is able to pick up on the status error code. Could you possibly post the URL of the article from which you sourced the code for me and maybe I could try it out tomorrow for myself after I've interpreted it in to c#. The web.config code looks alright to me, you've not namespaced any of it, so by all rights if you've cut and paste it word for word it should work but hey, these things happen. If I find anything more I'll let you know. Sorry I couldn't be much help.
Member
20 Points
25 Posts
Re: Custom 404 Error via iHTTPHandler
Jun 10, 2008 04:37 PM|kapcreations|LINK
let's say you have a web.config that looks like this:
<customErrors mode="On" defaultRedirect="~/Error.aspx">
<error statusCode="403" redirect="~/403Forbidden.aspx" />
<error statusCode="404" redirect="~/404PageNotFound.aspx" />
</customErrors>
If a user browses to a page that does not exist, the correct error page loads.
The problem, and it is a big problem, is that when the non existent page is accessed, IIS and .NET send out a 302 status code, that the resource has moved, and then loads the custom 404 page with IIS and .NET sending out a 200 status code. No where does it send out a 404 status code. Bad, Bad, Bad for SEO.
This can be verified by running Fiddler, or any other packet analytic software.
I have modified my 404PageNotFound.aspx to include:
Response.ClearHeaders()
Response.StatusCode = 404
But that does not do the trick either.
Bottom line is I want to get my iHTTPModule to work, and I can't seem to verify if it is even loading properly to intercept requests.
Member
20 Points
25 Posts
Re: Custom 404 Error via iHTTPHandler
Jun 10, 2008 04:39 PM|kapcreations|LINK
The page can be found at this url
Member
20 Points
25 Posts
Re: Custom 404 Error via iHTTPHandler
Jun 10, 2008 05:15 PM|kapcreations|LINK
using System.Web;
using System.Web.Configuration;
using System;
public class HttpErrorModule : IHttpModule
{
private void Context_Error(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
if((object.ReferenceEquals(context.Error.GetType(),typeof(HttpException))))
{
// Get the Web application configuration.
System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~/web.config");
// Get the section.
CustomErrorsSection customErrorsSection = (CustomErrorsSection)configuration.GetSection("system.web/customErrors");
// Get the collection
CustomErrorCollection customErrorsCollection = customErrorsSection.Errors;
int statusCode = ((HttpException)context.Error).GetHttpCode();
//Clears existing response headers and sets the desired ones.
context.Response.ClearHeaders();
context.Response.StatusCode = statusCode;
if ((customErrorsCollection.Get(statusCode.ToString()) != null))
{
context.Server.Transfer(customErrorsCollection.Get(statusCode.ToString()).Redirect);
}
else
{
context.Response.Flush();
}
}
}
#region IHttpModule Members
public void Dispose()
{
//Do nothing here
}
public void Init(HttpApplication context)
{
context.Error += new EventHandler(Context_Error);
}
#endregion
}
Member
20 Points
25 Posts
Re: Custom 404 Error via iHTTPHandler
Jun 10, 2008 08:18 PM|kapcreations|LINK
well, now I am convinced it is not even listening to requests.
I added the following line to init
Public Sub Init(ByVal context As System.Web.HttpApplication) Implements System.Web.IHttpModule.Init
Throw New HttpException("Exception Occured")
AddHandler context.Error, New EventHandler(AddressOf Context_Error)
End Sub
When I start the debugger, it just loads the home page of the project and does not throw the error leading me to believe it is not hooked incoming requests.
Thinking HttpErrorModule is a potential reserved word, I renamed my class and .vb file to myHttpErrorModule
My web.config now includes this entry:
<system.web>
<httpModules>
<add name="myHttpErrorModule" type="myHttpErrorModule" />
</httpModules>
</system.web>
Did something change in IIS 7 or VS 2008 that changes the way iHTTPModules are implemented in a .NET web application?
Member
20 Points
25 Posts
Re: Custom 404 Error via iHTTPHandler
Jun 11, 2008 10:39 AM|kapcreations|LINK
what could be causing this critical error? I have been hitting my head against the wall for three days now.
Member
31 Points
17 Posts
Re: Custom 404 Error via iHTTPHandler
Jun 11, 2008 03:20 PM|LukeJones|LINK
Hi Kap,
Thought I'd forgotten about you didn't you? I've tried out the c# version of this code today and I have to admit I like it, and it works better then my previous version, so might just have to update a site or two now. Wish I'd heard of this sooner.
The only problem I encountered using the c# version was that a current site I'm building that uses UrlReWriting.NET wouldn't Server.Transfer to non-existent pages which meant I had to use Response.Redirect instead - which I wasn't too bothered about considering I had no use for passing the error to the transferred page anyway. I suspect though this isn't your problem as your not using url rewrites, but you might want to try alterign the server.transfer method to use response.redirect. If you really need to use the error information in the transferred page then look at storing it in context via session or something.
I did namespace the HttpErrorModule code and alter the web.config to suit so my web.config looked like
Note that I altered the type and removed the module type information after the comma. This works fine with my application.
Your customErrors information in your web.config looks fine to me, but just keep mode='On' to make sure your seeing the correct page just in case it is working else you won't know -of course don't mean to patronise.
also add 'Imports System' - just in case (I'm comparing my code to yours here)
Next if it's still not working, post all the information in the Exception error. Copy it all to clip board and post it up here.
Hope any of this helps.
Regards,
Luke
Member
20 Points
25 Posts
Re: Custom 404 Error via iHTTPHandler
Jun 11, 2008 05:16 PM|kapcreations|LINK
Member
31 Points
17 Posts
Re: Custom 404 Error via iHTTPHandler
Jun 12, 2008 07:06 AM|LukeJones|LINK
Answer to 2. Yes I am storing this in my App_Code Folder. It's a folder or two deep but you probably know that folder structure in your App_Code folder means nothing as the directory is compiled as if no folders exist anyway. I do it as it just makes things easier to find that's all.
Answer to 4. That is just bizarre.
Answer to 6. Actually I was reading up on this implementation of Custom Errors and apparently this was designed intentionally and they have no plans to change it.
Copy and Paste the Web.Config information as well for you.
Hope any of this helps.
Member
20 Points
25 Posts
Re: Custom 404 Error via iHTTPHandler
Jun 12, 2008 06:10 PM|kapcreations|LINK
I've copied your code, and it does not work for me. Somehow either my module is not loading, or init is not hooking into the pipeline.
how can I debug this?
Member
20 Points
25 Posts
Re: Custom 404 Error via iHTTPHandler
Jun 12, 2008 06:18 PM|kapcreations|LINK
Since this is debugging in Vista with IIS 7, do I need to load my module from this section of web.config?
<system.webServer>
<modules>
</modules>
<handlers>
</handlers>
</system.webServer>
Member
20 Points
25 Posts
Re: Custom 404 Error via iHTTPHandler
Jun 12, 2008 06:25 PM|kapcreations|LINK
OOOhhhh. I am getting close.
If I go in IIS 7 and set the site to run under the Classic "Managed Pipeline Mode", it works as I thought it should. If I run it under the Integrated "Managed Pipeline Mode", it does not.
I think I am getting close!
Member
20 Points
25 Posts
Re: Custom 404 Error via iHTTPHandler
Jun 12, 2008 07:27 PM|kapcreations|LINK
I finally figured it out. Thank you so much for all of your help.
Evidently, IIS 7 in Vista / 2008 uses a new Managed Pipeline (which MS seems to assume everyone knows about)
What helped narrow it down is when I ran the site in IIS under Classic mode instead of Integrated mode. Since it finally worked in Classic mode, I could tell my module was not being called by IIS 7 from web.config.
I made the changes to my web.config to something along the lines of:
For IIS 6 (I already had this)
<system.web>
<httpModules>
<!-- IIS6 ASP.NET application settings (Classic mode) -->
<add name="CustomErrorModule" type="LJ.Store.BLL.CustomErrors.HttpErrorModule"/>
</httpModules>
</system.web>
And then I added this in so it works in IIS 7 as well (both this entry and the above entry can co-exist):
<system.webServer><validation validateIntegratedModeConfiguration="false"/>
<modules>
<!-- IIS7 application settings (Integrated mode) -->
<add name="CustomErrorModule" type="LJ.Store.BLL.CustomErrors.HttpErrorModule"/>
</modules>
</system.webServer>
after making that change, I got this error:
HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.
Module IIS Web Core
Notification BeginRequest
Handler Not yet determined
Error Code 0x800700b7
Config Error Cannot add duplicate collection entry of type 'add' with unique key attribute 'name' set to 'CustomErrorModule'
Config File \\?\C:\inetpub\wwwroot\web.config
so it is possible CustomErrorModule is a reserved key word in IIS 7, or perhaps it is just stuck in my GAC somewhere.
Regardless, I changed the filename from CustomErrorModule.vb to myCustomErrorModule.vb, renamed the class name within the file, and then modified web.config to show:
<system.web>
<httpModules>
<!-- IIS6 ASP.NET application settings (Classic mode) -->
<add name="myCustomErrorModule" type="LJ.Store.BLL.CustomErrors.HttpErrorModule"/>
</httpModules>
</system.web>
and
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/><modules>
<!-- IIS7 application settings (Integrated mode) -->
<add name="myCustomErrorModule" type="LJ.Store.BLL.CustomErrors.HttpErrorModule"/>
</modules>
</system.webServer>
It now works!!
These two links were a great help:
http://learn.iis.net/page.aspx/231/breaking-changes-for-aspnet-20-35-from-iis-60-to-iis-70-integrated-mode/
http://mvolo.com/blogs/serverside/pages/Redirect-requests-to-your-application-with-the-HttpRedirection-module.aspx
Member
20 Points
25 Posts
Re: Custom 404 Error via iHTTPHandler
Jun 12, 2008 08:00 PM|kapcreations|LINK
UPDATE, still not working...
new problem, and this is still a show stopper
Running the code through my VS debugger, I am able to hit break points in init and in Context_Error when I click on a bad url. Right before the redirect occurs, I look at the immediate window and ensure the status code is 404, which is is. Great! everything is working!
WRONG
If I run it outside of the debugger, it does not work
I rebuilt the solution, opened up IE, browsed to localhost, clicked on a bad link, and I still get the 302 to 200 redirect default ASP.NET redirect to my custom 404 page.
Checking further, I wanted to see how the module was loading outside the debugger.
To test, I modified init to
Public Sub Init(ByVal context As HttpApplication) Implements System.Web.IHttpModule.Init
Throw New HttpException("Exception Occured")
AddHandler context.[Error], AddressOf Context_Error
End Sub
When I opened IE, and tried to load the page, I got a nice fat error, of which I was expecting.
I move "Throw New HttpException("Exception Occured")" from init to the first line inside Context_Error, and then click on a bad link, nothing happens!
WTH?
How do I get my handler to override the built in asp.net error redirect?
and, even bigger, why am I able to trap the error in the debugger, and simulate exactly how I want it to work, but the live version does not emulate the same response?
This is caught in VS
Contributor
4057 Points
8649 Posts
MVP
Re: Custom 404 Error via iHTTPHandler
Jul 16, 2008 05:25 AM|haidar_bilal|LINK
Just my 2 $ in here :)
IIS 7.0 ships with a native module called CustomErrorModule that can be located inside the applicationHost.config file as follows:
<add name="CustomErrorModule" image="%windir%\System32\inetsrv\custerr.dll" />
The above module maps to the <httpErrors /> configuration section that allows you to define your own custom paths to errors and exceptions that might occur in your applicaiton.
So I believe the main reason for what was happening is that, you defined a module that has been already defined for you with the same name.
Either you remove the original module (which I don't recommend) through the <remove name="CustomErrorModule" /> element or simply use a different Name for the module you are registering!
Hope this clarifies the problem more!
Thanks
Professional ASP.NET 3.5 Security, Membership, and Role Management with C# and VB
Contributor
4057 Points
8649 Posts
MVP
Re: Custom 404 Error via iHTTPHandler
Jul 16, 2008 05:27 AM|haidar_bilal|LINK
Just my 2 $ in here :)
IIS 7.0 ships with a native module called CustomErrorModule that can be located inside the applicationHost.config file as follows:
<add name="CustomErrorModule" image="%windir%\System32\inetsrv\custerr.dll" />
The above module maps to the <httpErrors /> configuration section that allows you to define your own custom paths to errors and exceptions that might occur in your applicaiton.
So I believe the main reason for what was happening is that, you defined a module that has been already defined for you with the same name.
Either you remove the original module (which I don't recommend) through the <remove name="CustomErrorModule" /> element or simply use a different Name for the module you are registering!
Hope this clarifies the problem more!
Thanks
Professional ASP.NET 3.5 Security, Membership, and Role Management with C# and VB
None
0 Points
4 Posts
Re: Custom 404 Error via iHTTPHandler
Jul 18, 2008 11:19 AM|Dunc_nz|LINK
Hi,
This is something I've been chasing for quite some time now - the ability for asp.net to produce a 404 response code, and redirect to a friendly page.
I've replicated your code (I was previously doing something similar in global.asax.cs); problem I've got is that when you put an event hander on context.Error, the Application_OnAuthenticateRequest hasn't fired - so you don't have a session (context.Session = null). If I do a Server.Transfer, it goes to a friendly error page which inherits from a Master page that contains some basic functionality that reads the session, and it bombs out.
There *is* a session at this stage, I don't suppose you know of an alternative way of picking it up?
Thanks in advance,
Duncan
http://www.fluidfoundation.com
http://www.fluidstyle.co.uk
http://www.fluideating.co.uk
Member
10 Points
2 Posts
Re: Custom 404 Error via iHTTPHandlerModule and EventHandler
Jul 18, 2008 07:17 PM|NicheTank|LINK
I tried running this and it worked for me locally but not on a shared host. It turned out to be a permissions issue with reading the web.config.
Niche Tank
http://www.nichetank.com
Member
1 Points
16 Posts
Re: Custom 404 Error via iHTTPHandler
Sep 27, 2011 08:44 AM|vikas rathee|LINK
Could you please solve this issue. http://forums.asp.net/p/1724466/4614255.aspx
Please let me know..
Price Intelligence