Working with URL Routing in ASP.NET Framework 4.0

Introduction to the ASP.NET Framework

Microsoft's ASP.NET framework is a very successful web application development framework and has over the past few decades, matured to a state where it has become the best choice for developing highly scalable, high-performance web applications in a managed environment. Note that the ASP.NET 4.0 framework ships as part of Microsoft Visual Studio 2010. The Microsoft .NET Framework introduces a managed platform that opens a lot of possibilities - it provides a managed platform for executing applications that are portable, scalable, and robust. This article presents an overview of URL Routing and how the same can be implemented in ASP.NET 4 applications designed using Microsoft Visual Studio 2010.

Pre-requisites

To use the code examples illustrated in this article, you should have the following installed in your system:

  • Microsoft Visual Studio 2010

What's New in .NET Framework 4 and ASP.NET 4?

Microsoft's ASP.NET framework is a language and platform-neutral technology, arguably, one of the most successful web technologies ever. You can use it to design and develop web applications that can run on top of the managed environment of .NET Framework and inside the context of the IIS web server. URL Routing is a feature newly introduced in the ASP.NET framework. We will discuss more on it later in this article. Other notable new features in ASP.NET include the following:

  • State management improvements - enhancements to Cache and View State
  • Enhancements to ASP.NET data presentation controls
  • Enhanced Support for monitoring application performance
  • SEO enhancements
  • Simplified configuration

You can know more on these and other new features and enhancements in ASP.NET 4 from my book ASP.NET 4.0 Programming (McGraw-Hill Osborne Media).

Note that .NET Framework 4.0 ships as part of Microsoft Visual Studio 2010. The notable features provided by .NET Framework include: support for cross-language integration, the Common Type System, the Base Class Library, Common Language Runtime (CLR), the just-in-time (JIT) compiler, and automated garbage collection.

Microsoft .NET Framework 4 introduces a lot of new features and enhancements in the following areas:

  • The Dynamic Language Runtime
  • Managed Extensibility Framework
  • Support for Parallel Computing
  • ADO.NET, WCF and WWF

Search Engine Optimization and URL Routing in ASP.NET

URL Routing is a feature newly introduced in ASP.NET that allows you to configure your application to define user friendly URLs. This helps much in search engine optimization. Search Engine Optimization (commonly known as SEO) is a strategy used to increase traffic to a website. The Wikipedia states: "Search engine optimization (SEO) is the process of improving the visibility of a website or a web page in search engines via the "natural" or un-paid ("organic" or "algorithmic") search results." Reference: http://en.wikipedia.org/wiki/Search_engine_optimization.

You can use routing to define URLs that don't map to any particular physical file on the disk. Also, you can make use of routing in ASP.NET 4 to define custom routes. According to MSDN, "Routing is fundamentally about decomposing a URL endpoint into parameters and then using those parameters to steer the HTTP request processing to a specific component." Reference: http://msdn.microsoft.com/en-us/magazine/dd347546.aspx

You can now define user friendly and descriptive URLs in your ASP.NET applications to help optimize SEO. All you need to do is include the System.Web.Routing namespace and then define your routes accordingly. The System.Web.Routing namespace contains the necessary classes that you can use to implement URL rewriting in ASP.NET applications.

Implementing URL Routing in ASP.NET 4

In this section we will discuss how we can implement URL Routing in ASP.NET 4 applications using Microsoft Visual Studio 2010. To implement routing, the first thing you'll need to do is configure it in your application's configuration file. The following code snippet shows how you can configure the routing module into the ASP.NET pipeline using the <httpmodules> section of your application's configuration file:

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

If you were to implement routing in ASP.NET 4 using IIS 7.0, you'll need to specify routing module configuration in the modules section of the application's web.config file together with an entry to handle the incoming requests--you'll need to specify this entry in the section of your application's configuration file. Here's an example:

  <system.webServer>
     <modules runAllManagedModulesForAllRequests="true">
  
        <add name="UrlRoutingModule"
               type="System.Web.Routing.UrlRoutingModule, 
                     System.Web.Routing, Version=3.5.0.0, 
                     Culture=neutral, 
                     PublicKeyToken=31BF3856AD364E35" />
      </modules>
      <handlers>
  
        <add name="UrlRoutingHandler"
              preCondition="integratedMode"
              verb="*" path="UrlRouting.axd"
              type="System.Web.HttpForbiddenHandler, 
                    System.Web, Version=2.0.0.0, Culture=neutral, 
                    PublicKeyToken=b03f5f7f11d50a3a" />
      </handlers>
  </system.webServer>

The following code snippet illustrates how you can make use of the Page Meta Keyword and Description feature in ASP.NET 4.0.

  protected void Page_Load(object sender, EventArgs e)
  {
  
  this.Page.Title = "Code Guru";
  this.Page.MetaKeywords = "Internet.com";
  this.Page.MetaDescription = "This is a sample description.";
  }

The following code snippet illustrates how you can define routes in your application's Global.asax file:

  protected void Application_Start(object sender, EventArgs e)
  {
  	RegisterRoutes(RouteTable.Routes);
  }
  
  public static void RegisterRoutes(RouteCollection routes)
  {
  	routes.MapPageRoute("RouteToDepartments",
  	"Departments/{departmentName}",
  	"~/departments.aspx");
  }

You can then make use of the Page.RouteData.Values collection to check what is stored in it and then use appropriate logic in the page load event of your web page.

  string departmentName = Page.RouteData.Values["departmentName"].ToString();

The following code snippet illustrates how you can read data from this collection in the Page_Load event of your web form.

  protected void Page_Load(object sender, EventArgs e)
  {
  String departmentName = Page.RouteData.Values["departmentCode"].ToString();
  
  	if (department.Equals("HR"))
  	{
  	  Response.Write("HR Department");
  	}
  
  	else
  	{
    	  Response.Write("Other departments");
  	}
  }
  

Summary

URL Routing is a great feature newly introduced in ASP.NET that helps optimize SEO. The MSDN states: "The URL routing engine does all of the dirty work of URL pattern matching and URL generation. All you need to do is configure your routes and implement your route handlers." Reference: http://msdn.microsoft.com/en-us/magazine/dd347546.aspx.

In this article we discussed the basic the concepts of URL Routing - a feature newly incorporated in ASP.NET 4 and how we can develop applications that make use of URL Routing using ASP.NET 4 and Microsoft Visual Studio 2010.

Suggested Readings

Here are a few good links to resources on this topic for further study on this topic:



About the Author

Joydip Kanjilal

Microsoft Most Valuable Professional, Author and Speaker. Featured in "MSDN Featured Developer of the Fortnight (India)" a number of times. Winner of Community Credit Awards at www.community-credit.com several times. Authored numerous books and articles in Microsoft .NET and its related technologies. Authored the following books:-- ASP.NET 4.0 Programming (Mc-Graw Hill Publishing) Entity Framework Tutorial (Packt Publishing) Pro Sync Framework (APRESS) Sams Teach Yourself ASP.NET Ajax in 24 Hours (Sams Publishing) ASP.NET Data Presentation Controls Essentials (Packt Publishing)

Related Articles

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Data integrity and ultra-high performance dictate the success and growth of many companies. One of these companies is BridgePay Network Solutions, a recently launched and rapidly growing financial services organization that allows merchants around the world to process millions of daily credit card transactions. Due to the nature of their business, their IT team needed to strike the perfect balance between meeting regulatory-mandated data security measures with the lowest possible levels of latency and …

  • The 2014 State of DevOps Report — based on a survey of 9,200+ people in IT operations, software development and technology management roles in 110 countries — reveals: Companies with high-performing IT organizations are twice as likely to exceed their profitability, market share and productivity goals. IT performance improves with DevOps maturity, and strongly correlates with well-known DevOps practices. Job satisfaction is the No. 1 predictor of performance against organizational …

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date