7. Explain the role of filters in MVC and provide examples of when you would use them.

Advanced

7. Explain the role of filters in MVC and provide examples of when you would use them.

Overview

Filters in MVC play a crucial role in the execution pipeline, allowing developers to execute logic before or after specific stages in the request processing. They are essential for concerns such as authentication, authorization, caching, and error handling. Understanding filters is key to writing clean, modular, and efficient MVC applications.

Key Concepts

  1. Types of Filters: Understanding different filters like Authorization, Action, Result, and Exception filters and when to use them.
  2. Filter Execution Order: Knowing how filters are ordered and how this affects application behavior.
  3. Custom Filters: Creating custom filters for cross-cutting concerns, such as logging or performance measurement, that can be applied globally or on a per-action basis.

Common Interview Questions

Basic Level

  1. What are filters in MVC?
  2. Can you explain the purpose of Authorization filters?

Intermediate Level

  1. How does the MVC framework determine the order of filter execution?

Advanced Level

  1. Describe how you would implement a custom logging filter in an MVC application.

Detailed Answers

1. What are filters in MVC?

Answer: Filters in MVC are attributes that can be applied to controllers or actions to modify the way in which requests are handled. They provide a way to run code before or after certain stages in the MVC request processing pipeline, such as action method execution, authorization, and result execution. Filters are useful for handling cross-cutting concerns like logging, exception handling, and security in a clean and reusable way.

Key Points:
- Filters can be applied globally, to a controller, or to specific action methods.
- They help in managing cross-cutting concerns in an MVC application.
- There are several built-in filter types, including authorization, action, result, and exception filters.

Example:

public class LogActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Log action method execution start
        Log("OnActionExecuting", filterContext.RouteData);
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        // Log action method execution end
        Log("OnActionExecuted", filterContext.RouteData);
    }

    private void Log(string methodName, RouteData routeData)
    {
        var controllerName = routeData.Values["controller"];
        var actionName = routeData.Values["action"];
        Console.WriteLine($"Method: {methodName}, Controller: {controllerName}, Action: {actionName}");
    }
}

2. Can you explain the purpose of Authorization filters?

Answer: Authorization filters are a type of MVC filter that run before any other filters. Their primary purpose is to determine whether a user is authorized to perform the action they are requesting. This can involve checking if a user is authenticated, verifying permissions, or any other form of access control. If the user is not authorized, the filter can redirect the user to a login page or return an HTTP status code indicating the authorization failure.

Key Points:
- Authorization filters are executed first in the MVC filter pipeline.
- They are critical for security-related decisions.
- Custom authorization filters can be created for specialized security requirements.

Example:

public class CustomAuthorizationAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        // Custom authorization logic here
        bool isAuthenticated = httpContext.User.Identity.IsAuthenticated;
        // Assume a custom method IsUserAuthorized to check for specific permissions
        bool isAuthorized = isAuthenticated && IsUserAuthorized(httpContext.User);
        return isAuthorized;
    }

    private bool IsUserAuthorized(IPrincipal user)
    {
        // Implement your custom authorization logic, e.g., checking user roles or permissions
        return user.IsInRole("Admin");
    }
}

3. How does the MVC framework determine the order of filter execution?

Answer: The MVC framework determines the order of filter execution based on a combination of scope (Global, Controller, Action) and an explicit Order property that can be set on filters. Global filters are executed first, followed by Controller and then Action filters. Within each scope, filters can specify their execution order by setting the Order property. A lower Order value means the filter runs earlier within its scope. If no order is specified, it defaults to 0. Exception filters run in reverse order during exception handling.

Key Points:
- Filter execution order is determined by scope and the Order property.
- Global filters run before Controller and Action filters.
- Exception filters run in reverse order during exception handling.

Example:

[LogActionFilter(Order = 1)]
public class SampleController : Controller
{
    [CustomAuthorization(Order = 2)]
    public ActionResult Index()
    {
        return View();
    }
}

4. Describe how you would implement a custom logging filter in an MVC application.

Answer: Implementing a custom logging filter involves creating a class that inherits from one of the filter attribute classes, such as ActionFilterAttribute, and overriding its methods to include logging logic. This custom filter can then be applied globally, to a controller, or to specific action methods.

Key Points:
- Create a class that inherits from ActionFilterAttribute.
- Override the OnActionExecuting and/or OnActionExecuted methods to add logging.
- Apply the filter globally, to a controller, or to specific actions as needed.

Example:

public class CustomLoggingFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Log before the action executes
        Log("Start", filterContext.RouteData);
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        // Log after the action executes
        Log("End", filterContext.RouteData);
    }

    private void Log(string stage, RouteData routeData)
    {
        var controllerName = routeData.Values["controller"].ToString();
        var actionName = routeData.Values["action"].ToString();
        // Assuming a Log method exists to handle the log message
        Logger.Log($"{stage} - Controller:{controllerName}, Action:{actionName}");
    }
}

This custom logging filter can be applied to controllers or actions to provide detailed logs about the execution of action methods, aiding in debugging and monitoring MVC applications.