How to Implement AHSP.Net routing in Web Form and MVC Application. A route is an URL pattern that is mapped to a handler. The handler can be a physical file, such as, Default.aspx file in a Web Forms application. A handler can also be a class that processes the request, such as a controller in a 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.

In Web Form, we need to add route to the application by adding the Route object to the static Routes property of the RouteTable class. The Routes property is a RouteCollection object that stores all the routes for the application. MVC project includes preconfigured URL routes in Global.asax file by default.

URL Patterns in Web Form

A URL pattern may 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 (/) character. When a request is made, the URL is parsed into segments and placeholders, and the variable values are provided to the request handler. This process is similar to the way the data in query strings is parsed and passed to the request handler. In both cases variable information is included in the URL and passed to the handler in the form of key-value pairs. For query strings, both keys and values are included in the URL. For routes, the keys are placeholder names defined in the URL pattern and only values are in the URL.

In a URL pattern, placeholders are defined by enclosing them in braces “{ }”. There may be more than one placeholder in a segment and they can be separated by a literal value. For example, {company}/{customer}/{action} is a valid route pattern. However, {company}{customer}/{action} is not a valid route pattern, because there is no literal value or delimiter between the placeholders. So in this case, routing cannot determine as to where to separate the value for the company placeholder from the value for the customer placeholder.

The following table shows valid route patterns and examples of URL requests that match the patterns.

 

Route definition Example of matching URL
{controller}/{action}/{id} /Company/show/1001
{table}/Details.aspx /Cutomer/Details.aspx
blog/{action}/{entry} /aajblog/show/123
{reporttype}/{year}/{month}/{day} /sales/2008/1/5
{locale}/{action} /US/show
{language}-{country}/{action} /en-US/show

 

Adding Routes to a Web Forms Application

Routes are added in Application_Start event in the Global.asax file. It makes sure that the routes are available when the application starts. The following example shows code in Global.asax file. The code adds a Route object that defines two URL parameters named action and companyname. URLs that have the specified pattern are directed to the physical page named Company.aspx.

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

public static void RegisterRoutes(RouteCollection routes)
{
    routes.MapPageRoute("",
        "Company/{action}/{companyname}",
        "~/Company.aspx");
}

URL Patterns in MVC Applications

In MVC applications, URL patterns for routes include {controller} and {action} placeholders. For example, a URL that includes the URL path ‘/Company’ is mapped to a controller named CompanyController. The value in the action parameter is the name of the action method that is called. A URL that includes the URL path ‘/Company/View’ would result in a call to the View method of the CompanyController class.

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

 

Default URL pattern Examples of matching URL
{controller}/{action}/{id} http://server/application/Company/View/123

Adding Routes to a MVC Application

In MVC application, controllers classes are derived from ControllerBase class. You don’t need to manually add routes in an MVC application. The preconfigured routes will invoke the action methods that you implemented in the controller classes.

For custom routes in an MVC application, we need to use the MapRoute(RouteCollection, String, String) method instead of the MapPageRoute(String, String, String) defined under RoutConfig.cs class as given below.

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

        routes.MapRoute(
   "Default",                                                          "{controller}/{action}/{id
            new { controller = "Home", action = "Index", id = "" }  
        );
    }    
}

Setting Default values for URL Parameters in MVC and Web Form

When you define a route, the default value for a parameter can also be defined. The default value is used when the value for that parameter is not available in the URL. MapPageRoute(String, String, String, Boolean, RouteValueDictionary) method is used in RegisterRouts method to define default values for parameters as shown in  the example below for an ASP.NET Web application:

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

public static void RegisterRoutes(RouteCollection routes)
{
    routes.MapPageRoute("",
        "Company/{action}/{companyname}",
        "~/Company.aspx",
        true,
        new RouteValueDictionary 
            {{"companyname ", "xyz"}, {"action", "View"}});
}

* companyname = xyz and action = View are default values for parameters

Note: In MVC application, we define default values in MapPageRoute (String, String, String, Boolean, RouteValueDictionary) method in RoutConfig.cs file.

Handling a Variable Number of Segments in a URL Pattern in MVC and Web Form

Sometimes you have to handle URL requests that contain a number of URL segments. You can specify if a URL has more segments while defining a route. The extra segments are considered to be part of the last segment.

The following example shows a route pattern that matches an unknown number of segments.

query/{queryname}/{*queryvalues}

 

URL Parameter values
/query/select/bikes/onsale queryname = “select”

queryvalues = “bikes/onsale”

/query/select/bikes queryname = “select”

queryvalues = “bikes”

/query/select queryname = “select”

queryvalues = Empty string

 

Adding Constraints to Routes for MVC and Web Form

We can also define constraints to routes and can specify that values in the parameters meet certain constraints. If a URL contains values that are outside the constraints for a route, that route is not used to handle the request. You add constraints to make sure that the URL parameters contain values that will work in your application.

The following is an example of define constraints to route

public static void RegisterRoutes(RouteCollection routes)
{
    routes.MapPageRoute("",
        "Company/{action}/{companyname}",
        "~/Company.aspx",
        true,
        new RouteValueDictionary 
            {{"company", "xyz"}, {"action", "View"}},
        new RouteValueDictionary 
            {{"locale", "[a-z]{2}-[a-z]{2}"},{"year", @"\d{4}"}}
       );
}

The above code produces the following results when routing handles an URL request

 

URL Result
/US No match. Both locale and year are required.
/US/08 No match. The constraint on year requires 4 digits.
/US/2008 locale = “US”

year = “2008”