URL Routing in ASP.NET 4

Normally when you access a web page, you use a URL that is the physical path of the page. URL routing is a way to provide your own URL instead of the physical path.

ASP.NET 4.0 provides us with a simple and strong way to handle URL routing.

URL Routing

ASP.NET 4.0 router enables to define any kind of custom routes.

Example

I’m using visual studio 2010 for all my examples.

Step 1

In the Global.asax you have to define the Route in the Application_Start and include the namespace System.Web.Routing.

private void RegisterRoutes(RouteCollection routes)
{
    routes.MapPageRoute("category", "category/{0}/{1}/{2}", "~/Category.aspx");
    routes.MapPageRoute("product", "product/{0}/{1}/{2}/{3}", "~/Product.aspx");
}

protected void Application_Start(object sender, EventArgs e)
{
    RegisterRoutes(RouteTable.Routes);
}

Step 2

Create two web pages: Category.aspx and Product.aspx.

In the Page_Load of the page Product.aspx type the following:

protected void Page_Load(object sender, EventArgs e)
{
    StringBuilder stb = new StringBuilder();
    stb.AppendLine(Page.RouteData.Values["0"] as string);
    stb.AppendLine(Page.RouteData.Values["1"] as string);
    stb.AppendLine(Page.RouteData.Values["2"] as string);
    stb.AppendLine(Page.RouteData.Values["3"] as string);
    Response.Write(stb.ToString());
}

In the Page_Load of the page Category.aspx type the following:

protected void Page_Load(object sender, EventArgs e)
{
    StringBuilder stb = new StringBuilder();
    stb.AppendLine(Page.RouteData.Values["0"] as string);
    stb.AppendLine(Page.RouteData.Values["1"] as string);
    stb.AppendLine(Page.RouteData.Values["2"] as string);
    Response.Write(stb.ToString());
}

By doing this, we are fetching the parameters from the Routing Table.

Step 3:

In the browser, type the following URLs:

http://localhost/MyWebApplication/category/my/routing/url
http://localhost/MyWebApplication/product/my/first/routing/url

For the first URL, you will get the following output: “my routing url”.

For the second URL, you will get the following output: “my first routing url”.

According to the above example, the request is processed like this:

URL Routing Explained

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s