Wednesday, June 18, 2008

I've been looking at the routing infrastructure Microsoft are releasing in .NET 3.5 SP1. This is the infrastructure that allows me to bind an HTTP Hander to a URI rather than simply using webforms. It is used in the ASP.NET MVC framework that is in development. The infrastructure is pretty clean in design, First you add a reference to System.Web.Routing. Then you simply create Route objects binding a URI to an implementation of IRouteHandler. Finally you add it to a RouteTable static class. Global.asax is the ideal spot for this code.

void Application_Start(object sender, EventArgs e) 
{
        Route r = new Route("books", new BooksRouteHandler());
        RouteTable.Routes.Add(r);
        r = new Route("books/isbn/{isbn}", new BooksRouteHandler());
        RouteTable.Routes.Add(r);
        r = new Route("search/price", new SearchRouteHandler());
        RouteTable.Routes.Add(r);
}

Here BooksRouteHandler and SearchRouteHandler implement IRouteHandler

public interface IRouteHandler
{
    IHttpHandler GetHttpHandler(RequestContext requestContext);
}

So for example the BooksRouteHandler looks like this

public class BooksRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        if (requestContext.RouteData.Values.ContainsKey("isbn"))
        {
            string isbn = (string)requestContext.RouteData.Values["isbn"];
            return new ISBNHandler(isbn);
        }
        else
        {
            return new BooksHandler();
        }
    }
}

Where ISBNHandler and BooksHandler both implement IHttpHandler

This is all pretty straightforward. The one thing that had me puzzling for a while is who looks at the RouteTable. Reflector to the rescue! There is a module in the System.Web.Routing assembly called UrlRoutingModule. If you add this in to your web.config the routing starts working. The config piece looks like this

<httpModules>
      <add name="Routing" 
           type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpModules>


I'm currently using it to build a REST based service for the second part of a two part article for the DevelopMentor DevelopMents newsletter so if you're not on the distribution list for that subscribe!
 |  |  | 
Wednesday, June 18, 2008 8:36:52 AM (GMT Daylight Time, UTC+01:00)  #    Comments [1]TrackbackTracked by:
http://aspdotnetmvc.com/?tab=0 [Pingback]
Tuesday, August 19, 2008 6:37:19 AM (GMT Daylight Time, UTC+01:00)
ok, good!
share best site for you:
wow gold http://www.wowgolds.co.uk
广州电脑维修 http://www.boweipc.cn
Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):