Elmah in Web API 2 without MVC .Net 4.5.1

2.2k Views Asked by At

I am trying to implement Elmah error logging in an ASP.NET WEB API 2 project that doesnt use MVC.

I tried both Elmah and Elmah.mvc nuget packages and i am not even able to browse to the emlah page using both.

Is elmah supported in ASP.NET WEB API 2?

PS. I havent even started logging errors.I am just trying to browse to the page (elmah.axd in elmah or /elmah in elmah.mvc) and it is not accessible.

Edit: i am trying to implement the method mentioned in the blog.

http://blogs.msdn.com/b/webdev/archive/2012/11/16/capturing-unhandled-exceptions-in-asp-net-web-api-s-with-elmah.aspx

According to it, the elmah.axd page should be accesible right after the package is added. But it is not working for me.

update: Error Logging in working fine BTW. The only issue is I cant view error logs in the browser.

3

There are 3 best solutions below

1
On

Elmah is not currently supported in Web API because Web API does not use HttpContext. If you host a Web API under IIS then it is possible to access the HttpContext that comes from the hosting ASP.NET runtime.

Which host are you using? If it isn't IIS/ASP.NET runtime then you will not be able to use Elmah.

1
On

I ran into this problem because I had my web api configured to run from the root url instead of the 'api' path e.g. api.mydomain.com instead of mydomain.com/api. This caused the /elmah.axd path to be caught by the web api route and return the 404 error No type was found that matches the controller named 'elmah.axd'

To fix it I ignored the route in my Global.asax file with this:

protected void Application_Start()
{
    RouteTable.Routes.Ignore("{resource}.axd/{*pathInfo}"); 

    GlobalConfiguration.Configure(WebApiConfig.Register);
}

NOTE: Ignoring the route in the WebApiConfig routes section using config.Routes.IgnoreRoute(...) doesn't work, it has to be done using RouteTable.Routes.Ignore(...) as above.

I've also written a blog post on the next step - how to log all unhandled exceptions with elmah in Web API 2.1 at http://www.jasonwatmore.com/post/2014/05/03/Getting-ELMAH-to-catch-ALL-unhandled-exceptions-in-Web-API-21.aspx

0
On

This problem was driving me nuts - but with the Help of Jason and this post I was able to get it.

Prerequisites: You MUST be using IIS. Web Api doesn't use HttpContext, but you can get it from IIS.

  1. Install ELMAH using NuGet - (not Elmah MVC)
  2. Go to /elmah.axd - you will see ELMAH, but unstyled.
  3. Go to your Global.asax file and add the following to Application_Start():

RouteTable.Routes.Ignore("{resource}.axd/{*pathInfo}");

  1. Configure your implementation of Elmah.

NOTE: Step 3 must be done in the Golbal.asax - it will not work in the WebApiConfig.cs file for whatever reason. (Thanks Jason! ;) )

Hope this helps!