Skip to main content

ASP.NET Web API and ELMAH Integration

As you all probably heard, ASP.NET MVC 4 Beta is now available and has new features in it. One of them is that ASP.NET MVC has shipped with ASP.NET Web API (which was previously know as WCF Web API). Here is the quote from ASP.NET web site which explains what Web API Framework is all about shortly:
ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.
I am not going to give an into on ASP.NET Web API. There are great into tutorials and videos on ASP.NET web site for ASP.NET Web API. Instead, I will give you an example of a custom filter implementation.
A couple of months ago, I wrote a blog post about WCF Web API HttpErrorHandlersWCF Web API Plays Nice With ELMAH - A Quick Introduction to WCF Web API HttpErrorHandler. It works nicely on WCF Web API but this version of the framework, things a little bit changed. Instead of ErrorHandlers, we now have Filters which is more generic.
In order to make ELMAH work with ASP.NET Web API, we need to create a new Attribute which implements IExceptionFilter interface. Since we have ExceptionFilterAttribute (which implements the IExceptionFilter interface) available at the framework, we will derived from that class instead. Here is the whole implementation:
public class ElmahErrorAttribute : 
    System.Web.Http.Filters.ExceptionFilterAttribute {

    public override void OnException(
        System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext) {

        if(actionExecutedContext.Exception != null)
            Elmah.ErrorSignal.FromCurrentContext().Raise(actionExecutedContext.Exception);

        base.OnException(actionExecutedContext);
    }
}
Now we have our attribute, we need to tell the framework to use it. It is very straight forward as well. Here is how my Global.asax (Global.asax.cs) looks like:
public class WebApiApplication : System.Web.HttpApplication {

    protected void Application_Start() {

        Configure(
            System.Web.Http.GlobalConfiguration.Configuration
        );
    }

    private void Configure(HttpConfiguration httpConfiguration) {

        httpConfiguration.Filters.Add(
            new ElmahErrorAttribute()
        );

        httpConfiguration.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}
This will make Elmah log the errors. Now, you can configure ELMAH to send you an e-mail when an error occurred or you can log the error inside an XML file, SQL Server Database, wherever you what.
One more thing to mention about is that when you hit an error, the response will carry the exception details at the body of the response if you run your application locally. You can configure this option as well with the following configuration:
httpConfiguration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Never;

Comments

Popular posts from this blog

Top 10 ASP.NET Web API Interview Questions

What is ASP.NET Web API? ASP.NET Web API is a framework that simplifies building HTTP services for broader range of clients (including browsers as well as mobile devices) on top of .NET Framework. Using ASP.NET Web API, we can create non-SOAP based services like plain XML or JSON strings, etc. with many other advantages including: Create resource-oriented services using the full features of HTTP Exposing services to a variety of clients easily like browsers or mobile devices, etc. What are the Advantages of Using ASP.NET Web API? Using ASP.NET Web API has a number of advantages, but core of the advantages are: It works the HTTP way using standard HTTP verbs like  GET ,  POST ,  PUT ,  DELETE , etc. for all CRUD operations Complete support for routing Response generated in JSON or XML format using  MediaTypeFormatter It has the ability to be hosted in IIS as well as self-host outside of IIS Supports Model binding and Validation Support for OD...

Extension methods in C#

Consider the class C# 1 2 3 4 5 6 7 8 9 10 11 12 13          namespace ExtensionMethod      {          public class testClass {              public string sayHello ( ) {              return "Hello" ;            }        }      }     Invoke the above from your form using C# 1 2 3 4 5 6          testClass test = new testClass ( ) ;      MessageBox . Show ( test . sayHello ( ) ) ;     This will show “Hello” in message box. Consider the scenario where you don...

What is cookie? Advantages and disadvantages of cookies?

What is cookie? A cookie is a small piece of text file stored on user's computer in the form of name-value pair. Cookies are used by websites to keep track of visitors e.g. to keep user information like username etc. If any web application using cookies, Server send cookies and client browser will store it. The browser then returns the cookie to the server at the next time the page is requested. The most common example of using a cookie is to store User information, User preferences, Password Remember Option etc.It is also one of the common and mostly asked interview questions. Some facts about Cookie Here are a few facts to know about cookies: · Cookies are domain specific i.e. a domain cannot read or write to a cookie created by another domain. This is done by the browser for security purpose. · Cookies are browser specific. Each browser stores the cookies in a different location. The cookies are browser specific and so a cookie created in one browser(e.g in Google Chrome...