Custom HttpHandler in ASP.NET MVC

facebooktwittergoogle_plusredditpinterestlinkedinmail

There are many components and classes that support and manage an HttpRequest in ASP.NET, however, one of these items ultimately needs to generate some kind of response. That’s where HttpHandlers come in. These are the ASP.NET component that implement the IHttpHandler interface and generate a response to HttpRequst. The nature of HttpHandlers requires that only one can execute per request.

How to create an HttpHandler ?

Handler are actually pretty simple. We just need to create a class that implements the IHttpHandler interface and register it with our application and this can be done either through code or through a web.config. IHttpHandler interface exposes two memebers, a Boolean property of IsReusable and a method called ProcessRequest. IsReusable is just a flag that states whether the handler can be reused across requests. ProcessRequest method is the one that’s responsible for generating a response. The handler can respond to the request with almost anything, JSON , files , plain text , HTML and more. In this article we’ll look more closely at the MVC implementation of this.

The common uses for building your own handler might include customizing the behavior of existing frameworks . Another reason to implement a custom HttpHandler is if you are building your own framework so we are going to build a simple handler. The main concept that just want to illustrate is that requests that are intercepted by our customer handler will not be executed by the MVC handler, which means the MVC framework will not generate the response for that request. Let’s see how this works.

Create a ASP.NET MVC application and create a class that implements IHttpHandler interface. Now you can see the two members as we mentioned earlier.

  public class MyCustomHandler : IHttpHandler
    {
 
        public bool IsReusable
        {
            get { throw new NotImplementedException(); }
        }
 
        public void ProcessRequest(HttpContext context)
        {
            throw new NotImplementedException();
        }
    }

Now let’s just set the IsReusable to return false, that option isn’t all that important to us right now. I will just type out context.Response.Wriet and then let’s just add a line of HTML in here.

 
        public bool IsReusable
        {
            get { return false; }
        }
 
        public void ProcessRequest(HttpContext context)
        {
            context.Response.Write("<p>Hey !!! Howz my handler ?<p>");
        }

Next we need to register our handler with the application. We can do this either through code or using the web.config. Now I’m going to use code. To accomplish this let’s head over to our routeconfig file where we define all the routes for our application. You can see the default route for our MVC application is still there. Add new route and route handler there.

 
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.Add(new Route("home/contact", new MyRouteHandler()));
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
    public class MyRouteHandler : IRouteHandler
    {
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            return new MyCustomHandler();
        }
    }

Let’s go ahead and run the application. Click on contact menu.

Custom Httphandler demo
You can see the content from our custom handler. If you have breakpoint, you can see the MVC handler was never selected or executed, so that framework was never reached.

See Also
httpmodules and httphandlers in ASP.NET

The following two tabs change content below.

Tom Mohan

Tom Mohan is a technologist who loves to code and build. He enjoys working on Microsoft Technologies. Tom specializes in ASP.NET MVC, Web API , Azure, C# ,WPF, SQL etc and holds a Bachelor engineering degree in Computer Science. Certification : MCSD , MCTS