2

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";
}
Catalin
  • 11,503
  • 19
  • 74
  • 147
  • 1
    An HttpModule is more easy to integrate in other projects. Plus that i have access to other events as well, like BeginRequest – Catalin Jul 10 '16 at 10:17

1 Answers1

0

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());
VitalickS
  • 59
  • 1
  • 4