MVC Filters Interview Questions

ASP.NET MVC Filters Interview Questions and Answers

In this article, I will discuss Most Frequently asked MVC Filters Interview Questions and Answers.

What are ASP.NET MVC Filters and Attributes?

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 ASP.NET MVC filter interface or by inheriting and overriding methods of 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 mean 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 MVC?

Authorize (Restrict an action or controller to authorize user or role)

ChildActionOnly
HandleError (can specify a view to render in the event of an unhandled exception)

OutputCache (Cache the output of an action method)

RequireHttps
ValidateInput (Turn on/off request validation)

ValidateAntiForgeryToken (Helps prevent cross-site request forgeries)

Explain Different Filter Types in MVC?

ASP.NET MVC supports the following types of filters

Authorization Filter: 
  1. Class implementing IAutorizationFilter
  2. Eg: AuthorizeAttribute and RequireHttpsAttribute
  3. Can override the OnAuthorization method
Action Filter:
  1. Class implementing IActionFilter
  2. Eg: ActionFilterAttribute – used for writing the custom attribute
  3. Can override OnActionExecuting and OnActionExecuted
Result Filter:
  1. Class Implementing IResultFilter
  2. Eg: OutputChaceAttribute
  3. Can override OnResultExecuting and OnResultExecuted
Exception Filter:
  1. Class implementing IExceptionFilter
  2. Eg: HandleErrorAttribute

NOTE: Controller class implements all the above and we can override all the methods mentioned above.

What are the different types of Filters in ASP.NET MVC?

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

Authentication Filters: 

This filter is introduced with ASP.NET MVC5. The IAuthenticationFilter interface is used to create CustomAuthentication filter. The definition of this interface is given below-

public interface IAuthenticationFilter
{
    void OnAuthentication(AuthenticationContext filterContext);
    void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext);
}

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

public class CustomAuthenticationFilterAttribute : FilterAttribute, IAuthenticationFilter
{
    public void OnAuthentication(AuthenticationContext filterContext)
    {
        filterContext.HttpContext.Response.Write("Authentication Filter<br/>");
    }
    //Runs after the OnAuthentication method

    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
    {
        //TODO: Additional tasks on the request
    }
}
Authorization Filters: 

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 above methods of AuthorizeAttribute class.

Action Filters:

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:

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:

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

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

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

When Are Exception filters executed in ASP.NET MVC?

Exception filters are executed if there is an unhandled exception thrown during the execution of the ASP.NET MVC pipeline.

What is Custom action filters 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 allow 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 filter are executed in an order. The correct order of execution is given below:

  1. Authentication filters
  2. Authorization filters
  3. Action filters
  4. Result filters
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 Application_Start event of Global.asax.cs file with the help of FilterConfig class.

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 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.

Authorize attribute to allow us to ensure that the user is login before action/controller allow to process the request.

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

[AllowAnonymous]
public ActionResult NonSecureMethod()
{
    return View();
} 
What is the Use of 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 use 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.
Example:

The public action method that can be invoked using a URL request

public ActionResult Index()
{
    return View();
}

This method is accessible only by a child request. A runtime exception will be thrown if a URL request is made to this method

[ChildActionOnly]
public ActionResult Countries(List<String> countryData)
{
    return View(countryData);
}

What is the need of HandleErrorAttribute in MVC?

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

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

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 “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 OutputCache attribute in MVC?

OutputCacheAttribute is used to cache the content returned by a controller action method, so that, the same content does not need to be generated each and every time the same controller action is invoked.

[OutputCache(Duration = 10)]
public ActionResult Index()
{
    System.Threading.Thread.Sleep(3000);
    return View(db.Employees.ToList());
}

When we navigate to /Home/Index, the view output is cached for 10 seconds. If we refresh the view, within 10 seconds we will get a cached response. After 10 seconds, the cache expires, the code is executed again and the output is cached for another 10 seconds.

How to Cache specific portion of a view using ChildActionOnly attribute?

Step 1: Remove the OutputCache attribute and the line which calls Thread.Sleep(), from the Index() action method in HomeController. After the changes, the Index() action method should be as shown below.

public ActionResult Index()
{
    return View(db.Employees.ToList());
}

Step 2: Add GetEmployeeCount() action method to HomeController. Notice that, this method is decorated with OutputCache and ChildActionOnly attributes. 

// Child actions can be used to implement partial caching, 
// although not necessary. In this case, even if the ChildActionOnly
// attribute is removed, a portion of the view will be cached as expected
[ChildActionOnly]
[OutputCache(Duration = 10)]
public string GetEmployeeCount()
{
    return "Employee Count = " + db.Employees.Count().ToString() + "@ " +DateTime.Now.ToString();
}

Navigate to /Home/Index. Notice that, every time we refresh the page, the time in the section of the page that displays employee list changes, but not the time, that displays the employee count. This proves that only a portion of the view is cached. 

What is the use of RequireHttps in MVC?

[RequireHttps] attribute forces an unsecured HTTP request to be re-sent over HTTPS. . Let’s understand [RequireHttps] attribute with an example.

[RequireHttps]
public string Login()
{
    return "This method should be accessed only using HTTPS protocol";
}

Try to navigate to http://localhost/MVCDemo/Home/Login. Notice that you are automatically redirected to https://localhost/MVCDemo/Home/Login. So, [RequireHttps] attribute, forces an HTTP request to be re-sent over HTTPS.

RequireHttps attribute can be applied to a controller as well. In this case, it is applicable for all action methods within that controller.

Sensitive data such as login credentials, credit card information etc, must always be transmitted using HTTPS. Information transmitted over https is encrypted.  

How Authentication and Authorization work in ASP.NET MVC?

Like ASP.NET, MVC also supports Windows and Forms authentication. You can configure both the authentications by using Web.config or doing some custom code.

How Forms Authentication and Authorization work in ASP.NET MVC?

Like ASP.NET, MVC Forms authentication occurs after IIS authentication is completed. It can be configured by using forms element within Web.config file of your ASP.NET MVC application. The default attribute values for forms authentication are shown below:

SUMMARY

In this article, I try to explain most frequently asked MVC Filters Interview Questions and Answers. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

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