ASP.NET MVC Filters Interview Questions

ASP.NET MVC Filters Interview Questions and Answers

In this article, I am going to discuss the Most Frequently asked ASP.NET MVC Filters Interview Questions and Answers. Please read our previous article where we discussed the most frequently asked ASP.NET MVC Data Annotations Interview Questions with Answers. As part of this article, we are going to discuss the following ASP.NET MVC Filters Interview Questions and Answers.

  1. What are ASP.NET MVC Filters?
  2. Authentication Filters in ASP.NET MVC
  3. Authorization Filters in ASP.NET MVC
  4. Action Filters in ASP.NET MVC
  5. Result Filters in ASP.NET MVC
  6. Exception Filters in ASP.NET MVC
  7. What is Custom Action Filter in ASP.NET MVC?
  8. What is the order of execution of filters in ASP.NET MVC?
  9. How to Configure Filters in ASP.NET MVC?
  10. What is the Use of Authorize Action Filter in ASP.NET MVC?
  11. What is the Use of ChildActionOnly action filter?
  12. What is the need of HandleErrorAttribute in MVC?
  13. We did not apply the HandleError attribute anywhere. So how did all this work?
  14. What is the use of RequireHttps in MVC?
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 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 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 https 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 filters 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 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 to allow us to ensure that the user is log in 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 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 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 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 “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.

In the next article, I am going to discuss the most frequently asked ASP.NET MVC Caching Interview Questions with Answers. Here, in this article, I try to explain the most frequently asked ASP.NET MVC Filters Interview Questions and 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.

Leave a Reply

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