• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

ASP.NET MVC Routing Interview Questions and Answers

In this article, I am going to discuss the most frequently asked ASP.NET MVC Routing Interview Questions and Answers. Please read our previous article where we discussed some basic ASP.NET MVC Interview Questions with 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 that 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 you can define a route in ASP.NET MVC?
You can define a route in ASP.NET MVC as shown 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.
ASP.NET MVC Routing Interview Questions and Answers

Note: The point that you need to focus on is the route names must be unique across the entire application. Route names can’t be duplicated. Always put the more specific route on the top order while defining the routes, since the 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 the matching pattern.

What is Attribute Routing and how to define it in ASP.NET MVC?
The ASP.NET MVC5 supports a new type of routing called 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 Attribute 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.
MVC Routing Interview Questions and Answers

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.

Points to Remember while working with Attribute Routing:
  • We need to Configure the Attribute routing before the convention-based routing.
  • 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.
  • If you do not define any Conventional based Routing for your application and if you have action methods that 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 the ASP.NET MVC5 application just by making a call to the routes.MapMvcAttributeRoutes() method within RegisterRoutes() method of RouteConfig.cs file as shown below.
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        //enabling attribute routing 
        routes.MapMvcAttributeRoutes();
    }
}

Can we combine both attribute routing and convention-based routing in a single application?
Yes. 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
                }
        );
    }
}

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:
  • 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.
  • 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 the 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.

In the next article, I am going to discuss the most frequently asked Views and HTML Helpers Interview Questions in ASP.NET MVC Application with Answers. Here, in this article, I try to explain the most frequently asked ASP.NET MVC Routing Interview Questions with Answers. I hope this article will help you with your needs. I would like to have your feedback. Please post your feedback, question, or comments about this article.

0 comments:

Post a Comment

If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • Navigation Menus in ASP.NET Core
    In this article, I am going to discuss how to create Responsive Navigation Menus in ASP.NET Core Application using bootstrap and JQuery. P...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • ASP.NET State Management
    State management is a technique or way to maintain / store the state of an Asp.Net controls, web page information, object/data, and user in ...
  • HTTP Client Message Handler in Web API
    In this article, I am going to discuss HTTP Client Message Handler in Web API with real-time examples. As we already discussed in HTTP Mes...
  • Calling Web API Service in a Cross-Domain Using jQuery AJAX
    In this article, I am going to discuss Calling Web API Service in a Cross-Domain Using jQuery AJAX . Please read our previous article befor...
  • Authentication and Authorization in Web API
    In this article, I am going to discuss the Authentication and Authorization in Web API . Here I will give you an overview of Authentication...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape