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.
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.
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:
You can create your CustomAuthentication filter attribute by implementing IAuthenticationFilter as shown below:
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:
The AuthorizeAttribute class provides the following methods to override in the CustomAuthorize attribute class.
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.
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.
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.
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:
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.
2. Controller level – By putting your filter on the top of the controller name as shown below-
3. Action level – By putting your filter on the top of the action name as shown below-
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.
What is the Use of ChildActionOnly action filter?
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.
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.
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.
- Custom Authentication
- Custom Authorization (User-based or Role-based)
- Error handling or logging
- User Activity Logging
- Data Caching
- Data Compression
- Authorize (Restrict an action or controller to authorize user or role)
- ChildActionOnly (making an action method to be invoked as a child request)
- HandleError (can specify a view to render in the event of an unhandled exception)
- OutputCache (Cache the output of an action method)
- RequireHttps (converting https to https automatically)
- ValidateInput (Turn on/off request validation)
- ValidateAntiForgeryToken (Helps prevent cross-site request forgeries)
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:
You can create your CustomAuthentication filter attribute by implementing IAuthenticationFilter as shown below:
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:
- Authentication filters
- Authorization filters
- Action filters
- 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 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?
- Any action method that is decorated with [ChildActionOnly] attribute is a child action method.
- 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.
- Child action methods can be invoked by making child request from a view using “Action()” and “RenderAction()” HTML helpers.
- 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.
- Child actions are typically associated with partial views, although this is not compulsory.
- Child action methods are different from NonAction methods, in that NonAction methods cannot be invoked using Action() or RenderAction() helpers.
- Using child action methods, it is possible to cache portions of a view. This is the main advantage of child action methods.
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.
0 comments:
Post a Comment
If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.