I need to do routing in an existing asp.net app – not an asp.net mvc (yeah I know I should convert but let’s say it’s not possible right now so don’t tell me 🙂 ) – how can I do routing to a normal class instead of an aspx page as all sample code I see is always with aspx page like here:
http://msdn.microsoft.com/en-us/magazine/dd347546.aspx
To precise, I want to do a bit like in MVC Controller routing : the controller for example product is a pure class you access through http://domain.com/product
ASP.NET MVC and ASP.NET Web Forms share the same routing infrastructure in that both frameworks ultimately need to come up with an
IHttpHandlerto handle the HTTP request:In ASP.NET MVC the
System.Web.Mvc.MvcHandlerclass is used, which then delegates to a controller for further handling of the request. In ASP.NET Web Forms usually theSystem.Web.UI.Pageclass that represents an .aspx file is used, but a pureIHttpHandlerassociated with .ashx file can also be used.So you can route to an .ashx handler as an alternative to an .aspx Web Forms page. Both implement
IHttpHandler(as doesMvcHandler), but with the former that’s all it does. And that’s as close as you can get to a ‘pure class’ handling a (routed) request. And since the handler part is just an interface, you are free to inherit from your own class.Notice that an
IRouteHandlerjust needs to return an instance ofIHttpHandler:You may need to jump through some hoops to instantiate your handler using the BuildManager* if you use .ashx files. If not, you can just new up an instance of your class and return it:
See the answers to this question for much more in-depth analysis of routing pure IHttpHandlers: Can ASP.NET Routing be used to create “clean” URLs for .ashx (IHttpHander) handlers?
**I’m not entirely sure about the BuildManager example, someone please correct me if I got that part wrong*