HttpModule Error event not firing

594 Views Asked by At

I have an Asp.Net Web Api project, and i am trying to create a simple IHttpModule for logging errors.

The module gets loaded correctly, because i could register to BeginRequest / EndRequest events. However, the Error event is never triggered.

I have also added and removed the runAllManagedModulesForAllRequests="true" attribute from web.config, but still with no effect.

public class ErrorLogModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.Error += Context_Error;
    }

    // method never triggered
    private void Context_Error(object sender, EventArgs e)
    {
        HttpContext ctx = HttpContext.Current;
        Exception exception = ctx.Server.GetLastError();

        // todo
        // log Exception
    }

    public void Dispose()
    {

    }
}

<system.webServer>
  <modules runAllManagedModulesForAllRequests="true">
    <add name="ErrorLogger" type="HttpModules.HttpModules.ErrorLogModule" />
  </modules>
</system.webServer>

[HttpGet]
[Route("triggerError")]
public string TriggerError()
{
    int test = 0;
    var a = 1 / test;

    return "Hello Workd";
}
1

There are 1 best solutions below

0
VitalickS On

You can use better logging approach, that 100% working. See this Microsoft article.

Shortly speaking you can implement

YourExceptionLogger: ExceptionLogger

with just one override method and register it by

config.Services.Add(typeof(IExceptionLogger), new YourExceptionLogger());