Skip navigation.

How Non-Standard Web Code Hurts The Bottom LineAll recent postsCode Highlighter Is Now In Beta

Code-Behind For HTTP Handlers

I love poking around HTTP Modules and Handlers in ASP.NET. You can also see me quite often in HttpHandlers and HttpModules at the ASP.NET Forums. HTTP handlers and modules allow you to achieve something you were banned from in classic ASP (unless you were a hardcode C++ developer and could write an ISAPI with your eyes closed). Thanks to the power of the ASP.NET pipeline pretty much the only limitation is one's imagination.

Traditionally, a developer writes an HTTP handler by creating a class and implementing the IHttpHandler interface. Once you're done with the main bulk of the handler code, you need to plug it into the pipleline. You do so by registering it in web.config.

Few people realize that files with the .ashx extension are HTTP handlers as well. The SimpleHandlerFactory class, which is a handler factory, knows how to compile such a file and instantiate it as an implementation of the IHttpHandler interface. The nice thing about these handlers is you simply copy them to your application and place direct requests against them by typing a full URL. There's no need to register them in web.config and/or update IIS with extension mappings. They are a great fit for simple tasks.

You start off by creating an .ashx file and putting this line at the top:

<% @ WebHandler language="C#" class="MyCustomHandler" %> 

Many people in newsgroups complain that it's inconvenient to develop handlers this way because you get no code highlighting, no IntelliSense. Not friendly, indeed. However, you can have a code-behind file and enjoy all the benefits of ASPX pages. Let's extend the previous line of code:

<% @ WebHandler language="C#" class="MyCustomHandler" «
      codebehind="myhandler.cs" %>

You should be good to go now. Create myhandler.cs and start with

using System.Web;
public class MyCustomHandler: IHttpHandler {
...

Be aware of one gotcha: remember to specify the namespace! If you miss this you will receive "Parser Error Message: Could not create type 'MyCustomHanlder'." error.

For example, if MyCustomHandler resides in a namespace called MyNamespace be sure to include it in the .ashx file properly:

<% @ WebHandler language="C#" class="MyNamespace.MyCustomHandler" «
      codebehind="myhandler.cs" %>

The handler code should look as follows:

using System.Web;

namespace MyNamespace {
    public class MyCustomHandler: IHttpHandler {
...

Session State In HTTP Handlers

While on this subject, I'd like to also point out you should implement the IRequiresSessionState interface if you need to reference the Session object. It is simply a "marker" interface and as such doesn't have any members. It indicates that the handler needs read/write access to the session state.

If you omit this interface the first line that touches the session will blow up with the good old Object reference not set to an instance of an object message.

Comments

Comment permalink 1 Bharat |
How can I achieve smooth lines in chChartTypeColumn3D. Entire area looks jagged.

Your tip will be higly appriciated!

Thank you.

Bharat Gadhia
Comment permalink 2 Milan Negovan |
You can try and "quantize" it.
Comment permalink 3 afterburn |
Can not get URL rewrite to work from you examples.
Comment permalink 4 Milan Negovan |
What seems to be the problem?
Comment permalink 5 afterburn |
Lets explain.

IIS 6, using wildcard to catch all request and send to asp.net isapi extension. THen no front page extensions work.

In my hander I look for the something like so
http://mydomain.com/FirstName.LastName

First I check to see if its a real file using File.Exists on the PATH_TRANSLATED server variable. Also check to see if its a directory. If not any of the the above then I query db for information, using RewritePath to Default.aspx with query strings.
Default.aspx loads a template user control addes to the page betwen the form that has a corrected URL for post backs.

I got most of it to work but if I use the above I can not use front page extension to connect to web.
Comment permalink 6 Roshawn |
Great article! This is something that is completely new to me.

You stated that the ashx file could have its own code-behind file. How would you call the ProcessRequest() procedure the code-behind file (or any other procedure for that matter)? Or, is it as simple as typing a full URL?

Sorry if the question seems stupid, but I'm a newbie.

Thanks,
Roshawn
Comment permalink 7 Milan Negovan |
Your code-behind file (see the "@ WebHandler ......" declaration above) must declare ProcessRequest() because it derives from the IHttpHandler interface. Therefore ProcessRequest will always be invoked.

Does this answer your question or confuse you even more?
Comment permalink 8 Andrew Stone |
Just the info I was after! thanks very much! great site! keep up the good work!
Comment permalink 9 Claudiu |
I've been searching a lot and didn't find anything concret how to use the Session state from an http handler :(.
Comment permalink 10 Mohan Pal Singh |
I applie your code of pie chart in my application, this is not shown the image, how can i short out this problem.
Comment permalink 11 kevmil |
Nice example. Hopefully this will help some others. The recommendation to implement the interface IRequiresSessionState is a little confusing. It says "...if you need to reference the Session object." well, in order to get this to work you must reference the Session object. Try these additional steps:

1) add using System.Web.SessionState; to the web app client (default.aspx.cs)

2) inherit the interface IRequiresSessionState on the Page class of the web app client (default.aspx.cs)
(e.g. public class _default : System.Web.UI.Page, IRequiresSessionState)

Hopefully that will do it.
Comment permalink 12 kevmil |
One additional item required on my system in the web.config was enabling the session




Comment permalink 13 Deepak |
Hi
Great article.Excellent work in presenting concepts in such a lucid way.I have a question.How can we use handlers for folders.For example, for "things" that have no extension.

Example:
http://xyz.com/1
http://xyz.com/2
http://xyz.com/3

In the above, if all of them point to the same page, except that they are different ways to come to the same page(default.aspx).I do not want to create separate folders for 1,2,3.Instead I want to handle them and track them in one C# file and redirect them to
default.aspx.In the IIS application configuration mapping, I do not see an optin to add "no extension" or any pattern without a period(.). How do I do that?


Any ideas would be very appreciated.
THanks
Comment permalink 14 Inderjit |
Sir,
Actually i want the one connection class to be defined for my whole project and want that class to be inherited so that i dont have to write the full connection code repeated times .How can i use that class or module in asp.net code behind using C#.NET

As if I make my own class the how can i use it with codebehind system and how can I Inherit it in my code.

And i will wait for reply.

Reply me soon.
Comment permalink 15 Sanjay Sharma |
Thanks for such a Great Article !

Let provide me some code regarding how to use session variables with IHttpHandlers because it is not working even if I have Implemented System.Web.SessionState.IRequireSessionState.

Any help will be appreciable.
Thanks
Comment permalink 16 gices |
Hi Milan,

That's a really nice article on .ashx extension. At which stage is the ProcessRequest method called in the class btw?

Thanks,
gices
Comment permalink 17 Milan Negovan |
Look at the life cycle diagram in this article. It's under "The handler executes."
Comment permalink 18 BK |
Deepak: simply register .*
Comment permalink 19 mitesh |
Nice Article...
Comment permalink 20 Jay |
Awesome article! Thanks!
Comment permalink 21 Adrian |
About the .* wildcard in IIS:

I've been playing. .* works in IIS on winXP and 2000 server, but not on server 2003!!! This is most annoying! Or maybe there is some other wildcard to specify...

-A
Comment permalink 22 Sen Gupta |
Hello!

Great job! I was looking for something like this. My session was not working fine now I know why!

Thanks
Comment permalink 23 MTB |
I saw the article about using OWC11 for drawing charts which had a link to this article. Unfortunately even if I added the reference I can't use the charts.When I try to compile I get the error message saying "The type or namespace name 'OWC11' could not be found (are you missing a using directive or an assembly reference?)".

I tried to see if there's something wrong with the installation of OWC11. So I tried to draw a chart by opening Excel 2003 and it worked without any problem.So I think there's no error in installing and registering the component. Can any one help me please.
Comment permalink 24 Milan Negovan |
It sounds like an installation error. Just make sure you add a reference to OWC11 in Visual Studio.

Emails and Notifications

Would you like to be notified when somebody responds to this post?  Would you like to have these comments emailed to you?

TrackBacks

Sorry, TrackBacks are not allowed.

Submit your comment

Please enter only text since all HTML tags except hyperlinks will be stripped. Hyperlinks will become live links. Any comments with flaming or offensive language will be deleted. Be courteous to other posters. Thank you.

Your name (required):
Your email (optional):
Your site's URL (optional):
Enter this number
Type in the number above:
Comment (required):