How to create an Http Handle to re write the URL

This question keeps coming back to the ASP.NET forums, people wanting to write an Http Handler to re write the url. This is a common use in blogs and forums, when people wants to redirect from URL /blog/1093/post.aspx to /blog/post.aspx?id=1093 however keep the previous displayed for better url usage.

  • Create a class on the project and inherit from IHttpHandler

public class MyHandler : IHttpHandler

  • Right click the IHttpHander and select "Implement Interface" to create the method ProcessRequest and the property IsReusable.

#region IHttpHandler Members

public bool IsReusable
{
     get { return true; }
}

public void ProcessRequest(HttpContext context)
{
}

#endregion

The property will tell if can be reuse or create a complete new instance per request. By default is false to create a new instance per request.

PrecessRequest is where the guts are.

Server.Transfer("post.aspx?id=" + context.Request.Url.Segments[2]);

The last step is to register the HttpHandler on the web.config

<httpHandlers>
            <add verb="GET" path="post.aspx" type="yourNamespace.app_code.myhandler"/>

</httpHandlers>

Now all requests to post.aspx page will be handled by the httphadler, you'll still need to create a page that receives the parameters id or any other you need or a class instead of a page to handler your request. Remember to pass the http context.

Hopefully now I can answer with this post the Http Handler 101 question.

Cheers

Al

Published Tuesday, April 22, 2008 6:25 AM by albertpascual
Filed under: , , ,

Comments

# re: How to create an Http Handle to re write the URL

Tuesday, April 22, 2008 12:28 PM by AndrewSeven

I prefer to use a handler factory and serve the page at the requested url instead of re-writing it to something else

weblogs.asp.net/.../UrlRewriting.aspx

# re: How to create an Http Handle to re write the URL

Tuesday, April 22, 2008 3:16 PM by Joe Chung

Another alternative is to use the Routing functionality that was introduced in ASP.NET MVC.

Leave a Comment

(required) 
(required) 
(optional)
(required)