Usage of HttpHandler


HttpHandler can be very handy in scenario when you don't require complete page cycle.

Some important point related to HttpHandler
1. HttpHandler can be used when we introduced new script language. New file extension can
be handled by separate handler.
2. We can enable session access in httphandler
3. Syncronous Handler,Asynchronous handler
4. Can be used for performance enhancement.

Web.config entry for each handler.
< httpHandlers >
< add verb="*" path="*.< file extension > " type="< HandlerName > "/ >
< /httpHandlers >
HttpHandler - Usage


Typical Usage could be logging,authenticatio,performance enhancement e.t.c. User can directly
call the handler (.ashx) file and perform some task withough going through page lifecycle.

Usage 1 - .ashx file
scenario 1 - if we only want to return some file or response string then do we need to go through
page cycle.
.ashx file
< %@ WebHandler Language="C#" CodeBehind="Usage1Handler.ashx.cs" Class="DS_Mukesh.Usage1Handler" % >

.ashx.cs file
namespace DS_Mukesh
{
using System;
using System.IO;
using System.Web;


public class Usage1Handler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{


string fileName = "Usage1Handler";
Response.Clear();
Response.AppendHeader("Content-disposition", "attachment; filename=" + fileName);
Response.ContentType = "text/plain";
Response.Write(htmlText);
Response.Flush();
Response.End();
}

public bool IsReusable
{
get { return true; }
}

}

}

Usage 2 - .cs file
Scenario 2 - Want to do some caching for some request having special file extension. It will save
data tranmission. following can be done for file caching as well.

public class WebHandler : IHttpHandler
{
public WebHandler()
{

}


public void ProcessRequest(System.Web.HttpContext context)
{
context.Response.Cache.SetExpires(DateTime.Now.Add(600));
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Cache.SetValidUntilExpires(false);
< context.Response.writeFile(< some file name >);
}

public bool IsReusable
{
get
{
return true;
}
}

}




HttpHandler - Typical example

public class WebHandler : IHttpHandler
{
public WebHandler()
{

}


public void ProcessRequest(System.Web.HttpContext context)
{
HttpResponse httpResponse = context.Response ;
httpResponse.Write("

Hello World ") ;
httpResponse.Write("") ;
}

public bool IsReusable
{
get
{
return true;
}
}

}


HttpHandler - Asynchronous

using System;
using System.Web;
using System.Threading;

class AsyncHandler : IHttpAsyncHandler
{
public bool IsReusable { get { return false; } }

public AsyncHandler()
{
}
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback callBack, Object extraData)
{
SomeWork asynch = new SomeWork(callBack, context, extraData);
asynch.StartAsyncWork();
return asynch;
}

public void EndProcessRequest(IAsyncResult result)
{
}

public void ProcessRequest(HttpContext context)
{
throw new InvalidOperationException();
}
}

class SomeWork : IAsyncResult
{
private bool _completed;
private Object _state;
private AsyncCallback _callback;
private HttpContext _context;

bool IAsyncResult.IsCompleted { get { return _completed; } }
WaitHandle IAsyncResult.AsyncWaitHandle { get { return null; } }
Object IAsyncResult.AsyncState { get { return _state; } }
bool IAsyncResult.CompletedSynchronously { get { return false; } }

public SomeWork(AsyncCallback callback, HttpContext context, Object state)
{
_callback = callback;
_context = context;
_state = state;
_completed = false;
}

public void StartAsyncWork()
{
ThreadPool.QueueUserWorkItem(new WaitCallback(StartAsyncTask), null);
}

private void StartAsyncTask(Object workItemState)
{

_context.Response.Write("From Async Handler!");
_completed = true;
_callback(this);
}
}
Please see following link
http://msdn.microsoft.com/en-us/library/ms227433.aspx

HttpHandler - Synchronous
See below example
HttpHandler - SessionState(ReadOnly)

public class SessionReadOnlyHttpHandler : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
string Value = context.Session["SessionExample"] as String;
}

public bool IsReusable
{
get { return true; }
}
}

HttpHandler - SessionState(Read/Write)
public class SessionHttpHandler : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
string Value = context.Session["SessionExample"] as String;
Value = "Hello World";

context.Session["SessionExample"] = Value ;
}

public bool IsReusable
{
get { return true; }
}
}


Related Articles

HttpHandler

What is httphandler and why it is important

Optimizing ASP.NET Web application performance through Bundling and Minification Part-2

In the first article we had seen how Bundling helps us to minimize the number of HTTP requests sent from browser to improve ASP.NET web page performance. Now I am going to cover Minification Part which helps to reduce the size of requested resources to improve ASP.NET web page performance in terms of load time of CSS or JavaScript files(resources).

Website Performance boosting Tips

All functional and design efforts on a website are not worth untill its performance is good.This article is about website performance, containing 15 easy guidelines. If taken care by developers, can boost their website performance upto a desirable level. These tips are not restricted to any programming language.These can be implemented with any website developed using any technology.

More articles: HttpHandler Httpmodules ISAPI extensions Performance enhancements

Comments

Author: doug coppock17 Jul 2010 Member Level: Bronze   Points : 2

I have not been able to find any examples of how to invoke a .ashx asynch handler from a client AND make info available in the "extraData" object. Any idea how to do that? In a similar vein, how to invoke a .ashx asynch handler from a .aspx button control with other than setting the url of an image. For example, let's say I wanted to return a text file produced by a long running database query and wanted to pass the required parameters without using a query string, so params are located in "extraData" object.

public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback callBack, Object extraData)
{ }



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: