ASP.NET MVC Experienced Interview Questions and Answers

ASP.NET MVC Experienced Interview Questions and Answers

In this article, I am going to discuss the most frequently asked 35 ASP.NET MVC Experienced Interview Questions along with Answers. Please read our previous article where we discussed the most frequently asked basic 50 ASP.NET MVC Interview Questions with Answers.  I am sure at the end of this article, you will be in a better position to answer most of the ASP.NET MVC Experienced Interview Questions. As part of this article, we are going to discuss the following ASP.NET MVC Experienced Interview Questions with answers.

  1. What is Routing in ASP.NET MVC?
  2. How you can define a route in ASP.NET MVC?
  3. What is Attribute Routing and how to define it in ASP.NET MVC?
  4. When to use Attribute Routing in ASP.NET MVC Application?
  5. How to enable Attribute Routing in ASP.NET MVC?
  6. Can we combine both attribute routing and convention-based routing in a single application?
  7. What are Route Constraints in ASP.NET MVC?
  8. What is the difference between Routing and URL Rewriting?
  9. How is the routing table created in ASP.NET MVC?
  10. What is the use of the RoutePrefix attribute?
  11. How to override the route prefix? 
  12. What are Data Annotations in ASP.NET MVC?     
  13. Built-in Data Annotation Validator Attributes in ASP.NET MVC
  14. How to apply Server-side validation in ASP.NET MVC?
  15. How to determine there is no error in Model State?
  16. How to enable and disable client-side validation in ASP.NET MVC?
  17. What is a CDN and what are the advantages of using CDN?
  18. What is the jQuery Validation Unobtrusive plugin?
  19. What is Bundling and Minification in ASP.NET MVC?
  20. Can we use Bundling and Minification in ASP.NET MVC3 or ASP.NET MVC4?
  21. How Bundling uses browser Cache capability?
  22. What are ASP.NET MVC Filters?
  23. Authentication Filters in ASP.NET MVC
  24. Authorization Filters in ASP.NET MVC
  25. Action Filters in ASP.NET MVC
  26. Result Filters in ASP.NET MVC
  27. Exception Filters in ASP.NET MVC
  28. What is Custom Action Filter in ASP.NET MVC?
  29. What is the order of execution of filters in ASP.NET MVC?
  30. How to Configure Filters in ASP.NET MVC?
  31. What is the Use of Authorize Action Filter in ASP.NET MVC?
  32. What is the Use of the ChildActionOnly action filter?
  33. What is the need for HandleErrorAttribute in MVC?
  34. We did not apply the HandleError attribute anywhere. So how did all this work?
  35. What is the use of RequireHttps in MVC?
What is Routing in ASP.NET MVC?

This is one of the most frequently asked ASP.NET MVC Experienced Interview questions. Let discuss what is this in detail. In the ASP.NET MVC application, 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 from 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.

Routing Interview Questions and Answers in ASP.NET MVC

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 that do not have the Route attribute, then that action method will not be 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 is 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 these 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 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 Experienced 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 the 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.

What are Data Annotations in ASP.NET MVC?         

Data validation is a key aspect of developing a web application. In Asp.net MVC, we can easily apply validation to the web application by using Data Annotation attribute classes to the model class. Data Annotation attribute classes are present in System.ComponentModel.DataAnnotations namespace and are available to Asp.net projects like Asp.net web application & website, Asp.net MVC, Web forms and also to Entity framework ORM models. 

Data Annotations help us to define the rules to the model classes or properties for data validation and displaying suitable messages to end-users.

Built-in Data Annotation Validator Attributes in ASP.NET MVC          
  1. DataType – Specify the datatype of a property      
  2. DisplayName – specify the display name for a property.     
  3. DisplayFormat – specify the display format for a property like the different format for a Date property.        
  4. Required – Specify a property as required.             
  5. regular expression – validate the value of a property by the specified regular expression pattern. 
  6. Range – validate the value of a property within a specified range of values.  
  7. StringLength – specify min and max length for a string property.
  8. MaxLength – specify max length for a string property.
  9. Bind – specify fields to include or exclude when adding parameter or form values to model properties.
  10. ScaffoldColumn – specify fields for hiding from editor forms.
How to apply Server-side validation in ASP.NET MVC?

The Server-side validations are very important before playing with sensitive information of a user. Server-side validation must be done whether we validate the received data on the client-side. A user could disable the script in his browser or do something else to bypass client-side validation. In this case, server-side validation must require to protect our data from the dirty input. In ASP.NET MVC, there are two ways to validate a model on the server-side:

Explicit Model Validation in ASP.NET MVC

This is the traditional way to validate the model data by using IF..Else..IF statement. In this way, you need to check your model property values one by one for your desired result. If model property values are unexpected, inject error messages within ModelState.

public class HomeController : Controller
{
    [HttpPost]
    public ActionResult ExplicitServer(UserViewModel model)
    {
        //Write custom logic to validate UserViewModel
        if (string.IsNullOrEmpty(model.UserName))
        {
            ModelState.AddModelError("UserName", "Please enter your name");
        }

        if (!string.IsNullOrEmpty(model.UserName))
        {
            Regex emailRegex = new Regex(".+@.+\..+");
            if (!emailRegex.IsMatch(model.UserName))
                ModelState.AddModelError("UserName", "Please enter correct email address");
        }
        if (ModelState.IsValid) //Check model state
        {
            //TO DO:
        }
    }
}
Model Validation with Data Annotations in ASP.NET MVC

The Data Annotations were introduced with .NET 3.5 SP1. It has a set of attributes and classes defined in the System.ComponentModel.DataAnnotations assembly. Data Annotations allow us to decorate model classes with metadata. This metadata describes a set of rules that are used to validate a property.

ASP.NET MVC Data Annotations Interview Questions and Answers

How to determine there is no error in Model State?

When server-side model validation fails, errors are included in the ModelState. Hence, by using ModelState.IsValid property you can verify model state. It returns true if there is no error in ModelState else returns false.

[HttpPost]
public ActionResult DoSomething(UserViewModel model)
{
    if (ModelState.IsValid)
    {
        //TODO:
    }
    return View();
}
How to enable and disable client-side validation in ASP.NET MVC?

We can enable and disable the client-side validation by setting the values of ClientValidationEnabled & UnobtrusiveJavaScriptEnabled keys true or false. This setting will be applied to application level.

<add key=”ClientValidationEnabled” value=”true” />
<add key=”UnobtrusiveJavaScriptEnabled” value=”true” />

For client-side validation, the values of above both the keys must be true. When we create new project using Visual Studio in MVC3 or MVC4, by default the values of both the keys are set to true.

We can also enable the client-side validation programmatically. For this we need to do code within the Application_Start() event of the Global.asax, as shown below.

protected void Application_Start()
{
    //Enable or Disable Client Side Validation at Application Level 
    HtmlHelper.ClientValidationEnabled = true;
    HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
}

We can also enable or disable client-side validation for a specific view. For this, we required to enable or disable client-side validation inside a Razor code block as shown below. This option will override the application level settings for that specific view.

@using MvcApp.Models @{
    ViewBag.Title = "About";
    HtmlHelper.ClientValidationEnabled = false;
}
What is a CDN and what are the advantages of using CDN?

CDN stands for content delivery network or content distribution network (CDN) which is a large distributed system of servers deployed in multiple data centers across the Internet. The goal of a CDN is to serve the content (like the jQuery library and other open-source libraries) to end-users with high availability and high performance. There are three popular CDN – Google, Microsoft, and jQuery.

Google CDN: <script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js”></script>
Microsoft CDN: <script type=”text/javascript” src=”http://ajax.microsoft.com/ajax/jquery/jquery-1.9.1.min.js”></script>
JQuery CDN: <script type=”text/javascript” src=”http://code.jquery.com/jquery-1.9.1.min.js”></script>

Advantages of using CDN:
  1. It reduces the load from your application server.
  2. It saves bandwidth since jQuery and other open libraries/framework will load faster from these CDN.
  3. The most important benefit is it will be cached means if a user has visited any site which is using the jQuery framework from any of these CDN and your web application is also using the same CDN for serving the jQuery then for your application, it will not request the jQuery from CDN.
What is jquery.validate.unobtrusive.js? Or what is the jQuery Validation Unobtrusive plugin?

Microsoft introduced the jquery.validate.unobtrusive.js plugin with ASP.NET MVC3 to apply data model validations to the client-side using a combination of jQuery Validation and HTML 5 data attributes.

What is Bundling and Minification in ASP.NET MVC?

ASP.NET MVC4 and .NET Framework 4.5 offer bundling and minification techniques that reduce the number of requests to the server and size of requested CSS and JavaScript, which improve page loading time.

A bundle is a logical group of files that are loaded with a single HTTP request. You can create a style and script bundle for CSS and Java Scripts respectively by calling the BundleCollection class Add() method. All bundles are created within BundleConfig.cs file.

public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.min.css",
                       "~/Content/mystyle.min.css"));

        bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include("~/Scripts/jquery-1.7.1.min.js",
                        "~/Scripts/jquery.validate.min.js",
                        "~/Scripts/jquery.validate.unobtrusive.min.js"));
    }
}

Minification is a technique for removing unnecessary characters (like white space, newline, tab) and comments from the JavaScript and CSS files to reduce the size which causes improved load times of a webpage. There are so many tools for minifying the js and CSS files. JSMin and YUI Compressor are the two most popular tools for minifying js and CSS files.

Can we use Bundling and Minification in ASP.NET MVC3 or ASP.NET MVC4?

The System.Web.Optimization class offers the bundling and minification techniques that exist within Microsoft.Web.Optimization dll. Using this dll you can also use this technique with ASP.NET MVC3 and .NET Framework 4.0.

How Bundling uses browser Cache capability?

Browsers cache resources based on URLs. When a web page requests a resource, the browser first checks its cache to see if there is a resource with the matched URL. If yes, then it simply uses the cached copy instead of fetching a new one from the server. Hence whenever you change the content of CSS and JS files will not reflect on the browser. For this, you need to force the browser to refresh/reloading.

But bundles automatically take care of this problem by adding a hash code to each bundle as a query parameter to the URL as shown below. Whenever you change the content of CSS and a JS file then a new hash code will be generated and rendered to the page automatically. In this way, the browser will see a different Url and will fetch the new copy of CSS and JS.

What are ASP.NET MVC Filters?

ASP.NET MVC provides a simple way to inject some piece of code or logic either before or after an action is executed and this is achieved by decorating the controllers or controller action methods with ASP.NET MVC attributes or custom attributes. An attribute or custom attribute implements the ASP.NET MVC filters (filter interface) and can contain our piece of code or logic. We can make our own custom filters or attributes either by implementing the ASP.NET MVC filter interface or by inheriting and overriding methods of the ASP.NET MVC filter attribute class if available.

So if we need to add pre-and post-processing logic to an action method, then we need to use action filters.

Action filters are the attributes that can be applied either on a controller action method or on a controller. When they are applied at the controller level, then they are applicable for all actions within that controller. Action filters are basically custom classes that provide a means for adding pre-action or post-action behavior to controller actions. This means they allow us to modify the way in which an action is executed. 

Typically, Filters are used to perform the following common functionalities in your ASP.NET MVC application.

  1. Custom Authentication
  2. Custom Authorization (User-based or Role-based)
  3. Error handling or logging
  4. User Activity Logging
  5. Data Caching
  6. Data Compression
Name a few action filters in ASP.NET MVC?
  1. Authorize (Restrict an action or controller to authorize user or role)
  2. ChildActionOnly (making an action method to be invoked as a child request)
  3. HandleError (can specify a view to render in the event of an unhandled exception)
  4. OutputCache (Cache the output of an action method)
  5. RequireHttps (converting HTTP to HTTPS automatically)
  6. ValidateInput (Turn on/off request validation)
  7. ValidateAntiForgeryToken (Helps prevent cross-site request forgeries)
What are the different types of Filters in ASP.NET MVC?

The ASP.NET MVC framework provides five types of filters.

Authentication Filters in ASP.NET MVC: 

This filter is introduced with ASP.NET MVC5. The IAuthenticationFilter interface is used to create a Custom Authentication filter. The definition of this interface is given below:

ASP.NET MVC Filters Interview Questions and Answers

You can create your CustomAuthentication filter attribute by implementing IAuthenticationFilter as shown below:

ASP.NET MVC Filters Interview Questions with Answers

Authorization Filters in ASP.NET MVC: 

The ASP.NET MVC Authorize filter attribute implements the IAuthorizationFilter interface. The definition of this interface is given below:

public interface IAuthorizationFilter
{
    void OnAuthorization(AuthorizationContext filterContext);
}

The AuthorizeAttribute class provides the following methods to override in the CustomAuthorize attribute class.

public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
{
    protected virtual bool AuthorizeCore(HttpContextBase httpContext);
    protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext);
    public virtual void OnAuthorization(AuthorizationContext filterContext);
    protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext);
}

In this way, you can make your CustomAuthorize filter attribute either by implementing the IAuthorizationFilter interface or by inheriting and overriding the above methods of AuthorizeAttribute class.

Action Filters in ASP.NET MVC:

Action filters are executed before or after an action is executed. The IActionFilter interface is used to create an Action Filter which provides two methods OnActionExecuting and OnActionExecuted which will be executed before or after an action is executed respectively.

public interface IActionFilter
{
    void OnActionExecuting(ActionExecutingContext filterContext);
    void OnActionExecuted(ActionExecutedContext filterContext);
}
Result Filters in ASP.NET MVC:

The Result filters are executed before or after generating the result for an action. The Action Result type can be ViewResult, PartialViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult and EmptyResult which derives from the ActionResult class. Result filters are called after the Action filters. The IResultFilter interface is used to create a Result Filter which provides two methods OnResultExecuting and OnResultExecuted which will be executed before or after generating the result for an action respectively.

public interface IResultFilter
{
    void OnResultExecuted(ResultExecutedContext filterContext);
    void OnResultExecuting(ResultExecutingContext filterContext);
}
Exception Filters in ASP.NET MVC:

The Exception filters are executed when an exception occurs during the action execution or filter execution. The IExceptionFilter interface is used to create an Exception Filter which provides the OnException method which will be executed when an exception occurs during the action execution or filters execution.

public interface IExceptionFilter
{
    void OnException(ExceptionContext filterContext);
}

The HandleErrorAttribute class is an example of an exception filter that implements IExceptionFilter. When the HandleError filter receives the exception it returns an Error view located in the Views/Shared folder of your ASP.NET MVC application.

What is Custom Action Filter in ASP.NET MVC?

Actions are public methods in a controller. Action filters are attributes that can be applied either on a controller or on a controller action method, which allows us to add pre and post-processing logic to the action methods. 

So, in simple terms an action filter allows us to execute some custom code, either, just before an action method is executed or immediately after an action method completes execution. We have discussed some of the built-in action filters in the previous sessions of this series.

What is the order of execution of filters in ASP.NET MVC?

All ASP.NET MVC filters are executed in order. The correct order of execution is given below:

  1. Authentication filters
  2. Authorization filters
  3. Action filters
  4. Result filters

Note: The Exception filters are executed if there is an unhandled exception thrown during the execution of the ASP.NET MVC application.

How to Configure Filters in ASP.NET MVC?

We can configure your own custom filter into your application at the following three levels:

1. Global level – By registering your filter into the Application_Start event of Global.asax.cs file with the help of FilterConfig class as shown below.

protected void Application_Start()
{
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}

2. Controller level – By putting your filter on the top of the controller name as shown below-

[Authorize(Roles = "Admin")]
public class AdminController : Controller
{
    //TODO:
}

3. Action level – By putting your filter on the top of the action name as shown below-

public class UserController : Controller
{
    [Authorize(Users = "User1,User2")]
    public ActionResult LinkLogin(string provider)
    {
        // TODO: return View();
    }
}
What is the Use of Authorize Action Filter in ASP.NET MVC?

In ASP.NET MVC by default, all the controller action methods are accessible to both anonymous and authenticated users.  If we want action methods, to be available only for authenticated and authorized users, then we need to use the Authorize attribute. The Authorize attribute allows us to ensure that the user is log in before action/controller allows to process the request.

[Authorize]
public ActionResult SecureMethod()
{
    return View();
}

[AllowAnonymous]
public ActionResult NonSecureMethod()
{
    return View();
} 
What is the Use of the ChildActionOnly action filter?
  1. Any action method that is decorated with [ChildActionOnly] attribute is a child action method.
  2. Child action methods will not respond to incoming URL requests. If an attempt is made, a runtime error will be thrown stating – Child action is accessible only by a child request.
  3. Child action methods can be invoked by making child request from a view using “Action()” and “RenderAction()” HTML helpers.
  4. An action method doesn’t need to have [ChildActionOnly] attribute to be used as a child action but uses this attribute to prevent if we want to prevent the action method from being invoked as a result of a user request.
  5. Child actions are typically associated with partial views, although this is not compulsory.
  6. Child action methods are different from NonAction methods, in that NonAction methods cannot be invoked usingAction() or RenderAction() helpers.
  7. Using child action methods, it is possible to cache portions of a view. This is the main advantage of child action methods.
What is the need for HandleErrorAttribute in MVC?

HandleErrorAttribute is used to display friendly error pages to end-user when there is an unhandled exception

We did not apply the HandleError attribute anywhere. So how did all this work?

The HandleErrorAttribute is added to the GlobalFilters collection in global.asax. When a filter is added to the GlobalFilters collection, then it is applicable for all controllers and their action methods in the entire application. 

Right-click on the “RegisterGlobalFilters()” method in Global.asax, and select “Go To Definition” and we can find the code that adds “HandleErrorAttribute” to GlobalFilterCollection.

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
}
What is the use of RequireHttps in MVC?

The [RequireHttps] attribute forces an unsecured HTTP request to be re-sent over HTTPS.

Here, in this article, I try to explain the most frequently asked ASP.NET MVC Experienced Interview Questions with Answers. I hope you enjoy this ASP.NET MVC Experienced Interview Questions and Answers article. I would like to have your feedback. Please post your feedback, question, or comments about this ASP.NET MVC Experienced Interview Questions and Answers article.

Leave a Reply

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