HttpModule and HttpHandler

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.

posted @ 2007-03-29 12:56  29decibel  阅读(198)  评论(0)    收藏  举报