ASP.NET 4.0 Web Form routing

One of hundreds things I like about ASP.NET MVC, is the routing, a way to use clear and friendly URLs like: www.server.com/Customer/List, instead of something like www.server.com/Customers.aspx.

The routing part is now also added to the ASP.NET Web Form 4.0, so we can now use routing to avoid pointing to a .aspx file and ugly query stings. Scott Guthrie have wrote a blog post about it here. I will only write a short post to introduce it.

To define a route, we will use the Application_Start event of the Gloabal.asax file (a file which will be “executed” every time we visit a .aspx page). The Application_Start event will only be executed one time, and that is when the application starts (the first user visit our app). By using the static RouteTable class, we can add routes to the RouteTable’s Routes collection. This is done by using the MapPageRoute method. The MapPageRoute method can take some parameters, for example the name of the Route (to give a route an identifier so we can get and create routes in our code), the new URL where we also can specify parameters and route constraints etc. So for example if we have a URL look like this: www.server.com/Customer.aspx?id=10, we can use the Route feature to use a URL like this instead: www.server.com/Customer/10. The following code will setup this route:

 

void RegisterRoutes(RouteCollection routes)
{
      routes.MapPageRoute(
          "viewCustomerDetails",
         "Customer/{ID}",
        "~/Customer.aspx");
}

void Application_Start()
{
       RegisterRoutes(RouteTable.Routes);
}

I like this feature and will use it in all of my Web apps, where I need to use Web Forms, I will mostly use the ASP.NET MVC framework ;)

2 Comments

  • We are currently in the middle of converting our current url links to use URL Routing.

    Is it possible to have the same WebForm being loaded by the URL Routing (RouteData) and also the old ways with QueryString parameters in the URL?

    i.e.

    mysite.com/Books/456

    or

    mysite.com/Books.aspx?id=456

    The reason I ask is because we have thousands of links that have been given out to users and we do not want to break the current links.

    Thanks

  • MapPageRoute function is not comming

Comments have been disabled for this content.