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
Posted from http://weblogs.asp.net/albertpascual



Comments
Josh Stodola said on 5.02.2008 at 3:38 PM
Al, it's a better idea to use an HttpModule and catch the request earlier in the life cycle. Also, should be using the HttpContext.RewritePath method.
Best regards...