Code-Behind For HTTP Handlers

Posted on May 15, 2004  |  

Posted in Development

25 comments

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.

25 comments

Bharat
on November 23, 2004

How can I achieve smooth lines in chChartTypeColumn3D. Entire area looks jagged.

Your tip will be higly appriciated!

Thank you.

Bharat Gadhia


Milan Negovan
on November 23, 2004

You can try and "quantize" it.


afterburn
on January 18, 2005

Can not get URL rewrite to work from you examples.


Milan Negovan
on January 18, 2005

What seems to be the problem?


afterburn
on January 19, 2005

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.


Roshawn
on April 17, 2005

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


Milan Negovan
on April 18, 2005

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?


Andrew Stone
on June 7, 2005

Just the info I was after! thanks very much! great site! keep up the good work!


Claudiu
on February 28, 2006

I've been searching a lot and didn't find anything concret how to use the Session state from an http handler :(.


Mohan Pal Singh
on March 16, 2006

I applie your code of pie chart in my application, this is not shown the image, how can i short out this problem.


kevmil
on March 29, 2006

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.


kevmil
on March 29, 2006

One additional item required on my system in the web.config was enabling the session





Deepak
on June 13, 2006

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


Inderjit
on February 17, 2007

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.


Sanjay Sharma
on April 11, 2007

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


gices
on May 23, 2007

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


Milan Negovan
on May 23, 2007

Look at the life cycle diagram in this article. It's under "The handler executes."


BK
on October 10, 2007

Deepak: simply register .*


mitesh
on November 21, 2007

Nice Article...


Jay
on January 10, 2008

Awesome article! Thanks!


Adrian
on January 30, 2008

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


Sen Gupta
on February 15, 2008

Hello!

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

Thanks


MTB
on June 21, 2008

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.


Milan Negovan
on June 23, 2008

It sounds like an installation error. Just make sure you add a reference to OWC11 in Visual Studio.


Shahid F.
on November 11, 2009

Very useful article.

Just wanted to mention though that as it happened in my case, the Handler specifically '.ashx' was in a 'WebSite' type project (not Web Application) and since I am using Visual Studio Express edition, then the code behind only worked when I kept it under the App_Code folder. Unlike putting it along side the .ashx file.