ASP.NET 4.0 URL routing

I was reading ScottGu's blog the other day and decided to give the new URL routing in ASP.NET 4.0 a try.  Got it to work great, just register the routes in global.asax and then pull out the data on the page where you need it.

        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            RegisterRoutes(RouteTable.Routes);
        }

        void RegisterRoutes(RouteCollection routes)
        {
            routes.MapPageRoute("product-browse", "product/{name}_{id}", "~/Product.aspx");
            routes.MapPageRoute("category-browse", "category/{name}_{id}", "~/CategoryPage.aspx");
            routes.MapPageRoute("brand-browse", "brand/{name}_{id}", "~/BrandPage.aspx");
            routes.MapPageRoute("search", "search/{*searchTerms}", "~/Search.aspx");
        }

Above, I registered a route called product-browse where a page like http://mysite.com/product/some-great-toy_12 will get mapped to my Product.aspx page.  Inside Product.aspx, you would just need to retrive your id (and the name if you need it)

         string name = Page.RouteData.Values["name"] as string;
         int productId = Convert.ToInt32(Page.RouteData.Values["id"]);

Now, I have the productId, pulled right off the URL without using querystrings like I've used in the past.

I like it!

 

Comments (2) -

6/2/2011 9:07:45 AM #

IT Boca Raton

I recently need to rewrite some urls and I used 2.0 url mapping method, where all the mapped urls are in the web.config, you think this method is better?

IT Boca Raton United States | Reply

6/2/2011 1:18:04 PM #

scott

I switched from using Intelligencia's rewriter to the built in ASP.NET 4's routing because it was easier for me to figure out and create mappings.  It didn't clutter up my web.config and it was built in.  No external dependencies.  In the end, it probably does the same thing.  

scott United States | Reply

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading