ASP.NET MVC Routing Interview Questions and Answers

ASP.NET MVC Routing Interview Questions and Answers

In this article, I will discuss Most Frequently asked ASP.NET MVC Routing Interview Questions and Answers. Please read our previous article before proceeding to this article where we discussed some basic ASP.NET MVC Interview Questions and Answers.

What is Routing in ASP.NET MVC?

This is one of the most frequently asked ASP.NET MVC Routing Interview questions. Let discuss what is this in detail.

In ASP.NET MVC application, the Routing is nothing but a pattern matching mechanism which monitors the incoming request and then figures out what to do with that incoming request. At runtime, the Routing engine uses the Route table for matching the incoming request’s URL pattern with the URL patterns defined in the Route table. You can register one or more URL patterns to the Route table.

When the routing engine finds a match in the Route table for the incoming URL, then it forwards that request to the appropriate controller and action method. If there is no match found in the Route table, then it returns a 404 HTTP status code.

How to define a route in ASP.NET MVC?

You can define a route in ASP.NET MVC as given below. You can define any number of routes within the RegisterRoutes method of RouteConfig class. Then you need to call this method from the Application_Start event.

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

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

Note: The point that you need to focus on is the route names must be unique across the entire application. Route name can’t be duplicated.

In the above example, we have defined the Route Pattern as {controller}/{action}/{id} and we also provide the default values for the controller, action, and id parameters. Default values mean if we will not provide the values for controller or action or id parameter defined in the pattern then these values will be served as values for the controller, action, and id parameters by the routing engine.

Suppose your web application is running on www.dotnettutorials.com, then the URL pattern for your application will be www. dotnettutorials.com/{controller}/{action}/{id}. Hence you need to provide the controller name followed by action name and id if it is required. If you will not provide any of the value then default values of these parameters will be provided by the routing system. Here is a list of URLs that match and don’t match this route pattern.

Request URL        Parameters                                                                                    
  1. http://dotnettutorials.com/  => controller=Home, action=Index, id=none, since default value of controller and action are Home and Index respectively.                                                         
  2. http://dotnettutorials.com/Admin  => controller=Admin, action=Index, id=none, since default value of action is Index
  3. http://dotnettutorials.com/Admin/Product  =>     controller=Admin, action=Product, id=none
  4. http://dotnettutorials.com/Admin/Product/1 => controller=Admin, action=Product, id=1                   
  5. http://dotnettutorials.com/Admin/Product/SubAdmin/1  => No Match Found
  6. http://dotnettutorials.com/Admin/Product/SubAdmin/Add/1 => No Match Found

Note: Always put the more specific route on the top order while defining the routes, since routing system checks the incoming URL pattern form the top to bottom and if it gets the matched route it will consider that. It will not check further routes after matching pattern.

What is Attribute Routing and how to define it?

The ASP.NET MVC5 support a new type of routing called as attribute routing. In this case, we used attributes to define the routes either at the Controller level or at the action method level. The Attribute routing provides us the flexibility to define SEO friendly URLs very easily for our application. 

Controller level routing:

When we define routes at the controller level then they are applied to all the actions present within that controller until and unless we define some specific route to action. The following example shows how to define Routes at the Controller level.

[RoutePrefix("MyHome")]
[Route("{action=index}")] //default action
public class HomeController : Controller
{
    //new route: /MyHome/Index
    public ActionResult Index()
    {
        return View();
    }

    //new route: /MyHome/About
    public ActionResult About()
    {
        ViewBag.Message = "Your application description page."; return View();
    }

    //new route: /MyHome/Contact
    public ActionResult Contact()
    {
        ViewBag.Message = "Your contact page."; return View();
    }
}
Action level routing:

It is also possible that we can define the routes at the action method level which will apply to that action method on which it is applied.

public class HomeController : Controller
{
    [Route("users/{id:int:min(100)}")]
    //route: /users/100
    public ActionResult Index(int id)
    {
        //TO DO: 
        return View();
    }
    [Route("users/about")]
    //route" /users/about
    public ActionResult About()
    {
        ViewBag.Message = "Your application description page."; return View();
    }

    //route: /Home/Contact
    public ActionResult Contact()
    {
        ViewBag.Message = "Your contact page."; return View();
    }
}

Points to Remember while working with Attribute Routing:

  1. We need to Configure the Attribute routing before the convention-based routing.
  2. When we combine both attribute routing and convention-based routing, then the action methods which does not have the Route attribute will work according to the convention-based routing. In our example, the Contact action method is not decorated with the Route Attribute, so it is going to work according to convention-based routing.
  3. If you do not define any Conventional based Routing for your application and if you have action methods which do not have the Route attribute, then that action method will not be the part of attribute routing. In such cases, those action methods can’t be accessed from outside as a URI.
When to use ASP.NET MVC Attribute Routing?

It is very difficult to create certain URI patterns using convention-based routing which are common in Restful Services. But using the attribute routing, it is very easy to create those URI patterns.

For example, movies have actors, Clients have ordered, books have authors, Students have subjects, etc. This type of Restful URI is very difficult to create using our convention-based routing. But we can create this URI patterns very easily using the Attribute Routing. We need to decorate the Route attribute either at the Controller level or at the action method level as shown below:

[Route("clients/{clientId}/orders")]
public IEnumerable<Order> GetOrdersByClient(int clientId)
{
    //TO DO
}
How to enable Attribute Routing in ASP.NET MVC?

You can easily enable the attribute routing in ASP.NET MVC5 application just by making a call to the routes.MapMvcAttributeRoutes() method within RegisterRoutes() method of RouteConfig file as shown below.

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

It is also possible to combine both attribute routing and convention-based routing in a single application as shown below.

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

        //enabling attribute routing 
        routes.MapMvcAttributeRoutes();

        //convention-based routing 
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}
What are Route Constraints in ASP.NET MVC?

The Route constraint in ASP.NET MVC is a mechanism to add some validation around the defined routes.

Creating Route Constraints

Suppose we have defined the following route in our application and we want to restrict the incoming request URL with the numeric id only. Now let’s see how to do it with the help of regular expression.

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

        routes.MapRoute(
            name: "Default", //Route Name
            url: "{controller}/{action}/{id}", //Route Pattern
            defaults: new
            {
                controller = "Home", //Controller Name
                    action = "Index", //Action method Name
                    id = UrlParameter.Optional //Defaut value for above defined parameter
                }
        );
    }
}

Restrict to numeric id only

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(
            name: "Default", //Route Name
            url: "{controller}/{action}/{id}", //Route Pattern
            defaults: new
            {
                controller = "Home", //Controller Name
                    action = "Index", //Action method Name
                    id = UrlParameter.Optional //Defaut value for above defined parameter
                },
            constraints: new { id = @"\d+" } //Restriction for id
        );
    }
}

Now for this route, the routing engine will consider only those URLs which have only numeric id like as http://example.com/Admin/Product/1 else it will consider that URL is not matched with this route.

What is the difference between Routing and URL Rewriting?

This is one of the most frequently asked ASP.NET MVC Routing Interview Questions. Let us discuss the differences between Routing and URL Rewriting.

Nowadays, many developers compare the Routing mechanism with URL rewriting since both look similar and both are used to create SEO friendly URLs. But in reality, both are different. The main difference between routing and URL rewriting is given below:

  1. The URL rewriting is mainly focused on mapping one URL (new URL) to another URL (old URL) while Routing is focused on mapping a URL to a particular resource.
  2. URL rewriting rewrites the old URL to a new URL while the Routing never rewrites the old URL to a new URL rather it maps to the original route.
How is the routing table created in ASP.NET MVC?

When an MVC application first starts, the Application_Start() method of global.asax is called. This Application_Start() method calls the RegisterRoutes() method of RouteConfig class. The RegisterRoutes() method creates the Route table for ASP.NET MVC application.

What is the use of RoutePrefix attribute?

The RoutePrefix attribute in ASP.NET MVC application is used to specify the common route prefix at the controller level which will eliminate the need to repeat that common route prefix on each and every action method of the controller.

How to override the route prefix? 

To override the route prefix at the action method level, you need to use the ~ (tilde) character.

Leave a Reply

Your email address will not be published. Required fields are marked *