Search code examples
c#iis.net-assemblygachttpmodule

Custom error handling http module


I am trying to intercept the errors occurred in all the sites on a web server in order to do other useful stuff, such as logging.

As a starting point, I have

  1. Created http module which attaches an event handler to sites' error event.
  2. Created test MVC project with set of action methods throwing exceptions.
  3. Added the created http module class dll to GAC.

Http module class library is implemented as:

I have created a class library project with only one class extending IHttpModule. Please note that this is just a simplified version.

        using System;
        using System.Reflection;
        using System.Runtime.InteropServices;
        using System.Web;

        namespace MyWebModules
        {
            [ComVisibleAttribute(true)]
            public class MyErrorModule : IHttpModule
            {
                public void Dispose()
                {
                    throw new NotImplementedException();
                }

                public void Init(HttpApplication context)
                {
                    context.Error += new EventHandler(OnError);
                }

                private void OnError(object sender, EventArgs e)
                {
                    throw new Exception("Custom exception from MyErrorModule");
                    //TODO removed the above exception and add real life code here. 
                }
            }
        }

I added dll to GAC, by following the process below:

enter image description here

  1. Using csc.exe, I get ".netmodule" file from ".cs" code file
  2. ".snk" file is from the project.
  3. al.exe needs ".netmodule" and ".snk" to give strong name to the .dll
  4. With strong name, .dll is qualified to be added to GAC.

Testing using MVC test project.

Test site web.config has the following section.

<system.webServer>
  <modules runAllManagedModulesForAllRequests="true">
    <remove name="MyCustomWebModules" />
    <add name="MyCustomWebModules" type="MyWebModules.MyErrorModule,MyWebModules" />
  </modules>
</system.webServer>

When I access a test MVC site, I expect to see an error which says: "Custom exception from MyErrorModule"

Instead I get this error:

"Could not load file or assembly 'MisWebModules' or one of its dependencies. The system cannot find the file specified."


Solution

  • Ok. I got the version number wrong in web.config. I fixed that and it works.

    Comprehensive module tag in web.config file should contain the following GAC assembly details.

    • Dll info
    • version number
    • culture
    • public key token

    The following command can be used to see the details.

    gacutil /l