Routing ASP.NET/MVC

Asp.net Routing

 

ASP.NET routing enables you to use URLs that do not have to map to specific files in a Web site. Because the URL does not have to map to a file, you can use URLs that are descriptive of the user's action and therefore are more easily understood by users. Routing is pretty much rewriting but not necessarily the same.

In ASP.NET routing, you can define URL patterns that map to request-handler files, but that do not necessarily include the names of those files in the URL. In addition, you can include placeholders in a URL pattern so that variable data can be passed to the request handler without requiring a query string.

The Route is equivalent a URL Pattern.

A route is a URL pattern that is mapped to a handler. The handler can be a physical file, such as an .aspx file in a Web Forms application. A handler can also be a class that processes the request, such as a controller in an MVC application. To define a route, you create an instance of the Route class by specifying the URL pattern, the handler, and optionally a name for the route.

 

Here I will show you how to implement it both in ASP.NET Web Forms and MVC Proyect:

 

ASP.NET Routing:

First what we can do as a quick example is creating a webform proyect and then add 3 web forms on it. Page1, Page2 and Page3. On page1 add 3 buttons on design view.

 

Page1.aspx

<div>

<asp:Label ID="Label1" runat="server" Text="My Link 1"></asp:Label>

<asp:Button ID="Button1" runat="server" Text="Link1" OnClick="Button1_Click" />

<br />

<asp:Label ID="Label2" runat="server" Text="My Link 2"></asp:Label>

<asp:Button ID="Button2" runat="server" Text="Link2" OnClick="Button2_Click" />

<br />

<asp:Label ID="Label3" runat="server" Text="My Link 3"></asp:Label>

<asp:Button ID="Button3" runat="server" Text="Link3" OnClick="Button3_Click" />

</div>

 

 

Go to the code source and on each button add the following code.

 

protected void Button1_Click(object sender, EventArgs e)

{

//Response.Redirect("page2.aspx");

Response.Redirect(GetRouteUrl("SecondRoute", null));

}

protected void Button2_Click(object sender, EventArgs e)

{

//Response.Redirect("page3.aspx?FirstName=Daniel");

Response.Redirect(GetRouteUrl("ThirdRoute", new {FirstName="Daniel", LastName="Sauer" }));

}

protected void Button3_Click(object sender, EventArgs e)

{

//Response.Redirect("page3.aspx?LastName=Sauer");

Response.Redirect(GetRouteUrl("ThirdRoute", new { FirstName="Cristian", LastName = "Saüer" }));

}

 

 

As you can see I commented in Green color the alternative way not using RouteTables to redirect it in order for you to note the differences.

 

 

On Page3.aspx

Here you will catch the query string passed from page1.As we will make use of Routes we have to do it this way. Again, I commented in green color the normal way not using routes. On page2 you can add the same with dif.values.

 

public partial class page3 : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

// Response.Write("First Name: " + Request.QueryString ["FirstName" ]);

Response.Write("FirstName: " + RouteData.Values["FirstName"]);

Response.Write("<Br />");

Response.Write("LastName: " + RouteData.Values["LastName"]);

}

}

 

 

 

Global.Asax

Here you should register RouteTables and map the requests choosen.

As you can see the first name is the route name the second value is the url reuquest and the third value is the mapped file which that request will point to without user can note about that.

 

 

 

namespace ASPnetRouting

{

public class Global : System.Web.HttpApplication

{

protected void Application_Start(object sender, EventArgs e)

{

RegisterRoutes(RouteTable.Routes);

}

void RegisterRoutes(RouteCollection routes)

{

routes.MapPageRoute("FirstRoute", "First", "~/page1.aspx");

routes.MapPageRoute("SecondRoute", "Second", "~/page2.aspx");

routes.MapPageRoute("ThirdRoute", "Third/ {FirstName} - {LastName}", "~/page3.aspx");

}

}

}

 

 

A URL pattern can contain literal values and variable placeholders (referred to as URL parameters). The literals and placeholders are located in segments of the URL which are delimited by the slash (/) carácter.

When you browse you will see that by convention this work!

 

 

MVC Routing:

 

 

URL patterns for routes in MVC applications typically include {controller} and {action} placeholders.

When a request is received, it is routed to the UrlRoutingModule object and then to the MvcHandler HTTP handler. The MvcHandler HTTP handler determines which controller to invoke by adding the suffix "Controller" to the controller value in the URL to determine the type name of the controller that will handle the request. The action value in the URL determines which action method to call.

For example, a URL that includes the URL path /Products is mapped to a controller named ProductsController. The value in the action parameter is the name of the action method that is called. A URL that includes the URL path /Products/show would result in a call to the Show method of the ProductsController class

The following table shows the default URL patterns, and it shows examples of URL requests that are handled by the default routes.

Default URL pattern Examples of matching URL
{controller}/{action}/{id} https://server/application/Products/show/beverages
{resource}.axd/{*pathInfo} https://server/application/WebResource.axd?d=...

 

 

For IIS 7.0, no file-name extension is needed. For IIS 6.0, you must add the .mvc file-name extension to the URL pattern, as in the following example:{controller}.mvc/{action}/{id}

 

The following example shows code from a Global.asax file that adds a Route object that defines two URL parameters named action and categoryName. URLs that have the specified pattern are directed to the physical page named Categories.aspx.

 

protected void Application_Start(object sender, EventArgs e)

{

RegisterRoutes(RouteTable.Routes);

}

 

public static void RegisterRoutes(RouteCollection routes)

{

routes.MapPageRoute("",

"Category/{action}/{categoryName}",

"~/categoriespage.aspx");

}

 

Another example :

 

public class MvcApplication : System.Web.HttpApplication

{   public static void RegisterRoutes(RouteCollection routes)

{       routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(  "Default",             "{controller}/{action}/{id}",

new { controller = "Home", action = "Index", id = "" }        );

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

}

 

 

 

 

Remark: making use of MVC routing is better user friendly than asp.net routing you can set default values as an example here:

routes.MapPageRoute("",       "Category/{action}/{categoryName}",       "~/categoriespage.aspx",       true,       new RouteValueDictionary            {{"categoryName", "food"}, {"action", "show"}});

 

You can set constrainsts as an example here :

public static void RegisterRoutes(RouteCollection routes){   routes.MapPageRoute("",       "Category/{action}/{categoryName}",       "~/categoriespage.aspx",       true,       new RouteValueDictionary

{{"categoryName", "food"}, {"action", "show"}

},      new RouteValueDictionary            {{"locale", "[a-z]{2}-[a-z]{2}"},{"year", @"\d{4}"}}       );

}

 

Constraints are defined by using regular expressions or by using objects that implement the IRouteConstraint interface. When you add the route definition to the Routes collection, you add constraints by creating a RouteValueDictionary object that contains the verification test. The key in the dictionary identifies the parameter that the constraint applies to. The value in the dictionary can be either a string that represents a regular expression or an object that implements the IRouteConstraint interface.

 

You can also specify that routing should not handle certain URL requests

public static void RegisterRoutes(RouteCollection routes){ routes.Ignore("{resource}.axd/{*pathInfo}");}

 

Hope this quick walkthough can help you understand about Routing both in MVC and ASP.NET Proyects.