ASP.NET MVC filter are usedto inject extra logic in different levels of MVC Framework request processing. Filter provides a way for cross-cutting concerns (logging, authorization, and caching).
Filters is a custom class and can write custom logic to execute before or after in action method executes. Filter can be applied to the action method or controller in a declarative or programmatic way. There is a declarative means by apply in a filter attribute to the action method or controller class and programmatic means by implementing in corresponding interface.
Types of Filters in ASP.NET MVC
There are five types of Filters in ASP.NET MVC
Authorization Filter
The authentication filter runs before any other filter or action method. The authentication confirms that if you are a valid or invalid user. Action filters implement the IAuthenticationFilter interface.
Authorization Filter
The AuthorizeAttribute and RequireHttpsAttribute is example of Authorization Filters. The Authorization Filters are responsible for checking User Access. These implement the IAuthorizationFilterinterface in the framework. This filter is used to implement authentication and authorization for controller actions.Example of the Authorize filter is an example of an Authorization filter.
Result Filters
The result filters arean example of outputCacheAttribute class.The implementation of IResultFilter interface which looks like the IActionFilter has OnResultExecuting and OnResultExecuted. The filter contains in logic that is executed before and after a view result is executed. If you want to modify a view result and right before the view is rendered to the browser.
ExceptionFilters
The HandleErrorAttribute class is an example of ExceptionFilters. The implementation of IExceptionFilter interface and they execute if there are any unhandled exceptions thrown during the execution pipeline. This filter can be used as an exception filter to handle errors raised by either your controller actions or controller action results
Read More: What Is Cross-site Request Forgery (Csrf) In Asp.net Web Applications?
Action Filters
There is an action filter are attribute that you can apply to a controller action or an entire controller. This filter will call on before and after the action starts executing and after the action has executed.
Action filters implement the IActionFilter interface in two methods OnActionExecutingandOnActionExecuted. First method is OnActionExecutingwhich runs before the Action and gives an opportunity to cancel the Action call. This filter contains a logic that is executed before and after a controller action executes, you can use an action filter, for instance, to modify the view data that a controller action return.
Action filterexecutes before and after an action method executes. Action filter attribute can be applied to individual action method or to a controller. It is applied to a controller and to all the controller's action methods.
Action filters are the custom classes that allows you to inject pre or post processing logic before the action method gets executed. It can be created by inheriting a class with actionFilterAttribute and can override any of the action method.
An action filter is an attribute that you can apply to a controller action or an entire controller that modifies the way in which the action is execute. TheASP.NETMVC framework includes several action filters
- HandleError
- Outputcache
- Authorize
You can override the methods in your controller class.
Filter type
Authentication filter
Authorization filter
Action filter
Result filter
Exception filter
Implemented by
IAuthenticationFilter
IAuthorizationFilter
IActionFilter
IResultFilter
IExceptionFilter
Creating a Simple Action Filter Example in Asp.Net MVC project
Step 1: -Open visual studio and click on File ->New->Project menu option
A new Project Dialog open.
Step 2: -In the left pane, select templates ->visualC# ->Web
Step 3: -Then, select ASP.NET WEB Application (.NET Framework)
Step 4: -Enter project name ActionFilterDemo in the Name Field and click ok to continue and you will see the dialog.
Step 5: -Select MVC option and check the MVC checkbox then click Ok
Example of HandleError in Action Filters
HandleError: - Handles error raised when a controller action is executed. ASP .NET MVC has a HandleError Attribute (Action Filter), which provides one of the simplest ways to handle errors. The Attribute of HandleError has a couple of properties which are useful in handling an exception and help in modifying the default behavior of HandleError Attribute
Step 1: -I have create anActionFilterDemo project. Then select a View in shared Folder ->Error.cshtml. Error.cshtml file Use in ActionFilterdemo project
Step 2: - To add controller,Right-click on the controller folder in the solution explorer and select ADD -> Controller It will display the Add Scaffold dialog.
step 3: - Select the MVC 5 Controller -> Empty option and click on ADD button The Add controller dialog will show
Step 4: - set the Name to UserController and click on add button
CacheController.cs
The CacheController specifies the return value in 10 seconds
namespaceActionFilterDemo.Controllers
{
publicclassCacheController : Controller
{
// GET: Cache
[OutputCache(Duration =10)]
publicstringIndex()
{
returnDateTime.Now.ToString();
}
}
}
Now Run in ActionFilterDemoProject. It will be display output in Outputcache
Searching for Dedicated ASP.Net Web Developer? Your Search ends here.
Example of Authorize in Action Filters
Authorize: - Enables you to restrict access to a particular user or role. All the action methods are accessible to the both anonymous and authenticated users. But, the action methods to be available only for authenticated and authorized users, then you need to use the AuthorizationFilter in MVC.
Step 1: -To add controller, Right-click on the controller folder in the solution explorer and select ADD -> Controller. It will display the Add Scaffold dialog.
step 2: -select the MVC 5 Controller -> Empty option and click on ADD button
Step 3: - set the Name to AuthorizeController and click on add button
AuthorizeController.cs
The Authorized allows only authorized users to log in the application.
namespaceActionFilterDemo.Controllers
{
publicclassAuthorizeController : Controller
{
// GET: Authorize
publicActionResultIndex()
{
returnView();
}
[Authorize]
publicActionResultSaved()
{
returnView();
}
[AllowAnonymous]
publicActionResultNot_saved()
{
returnView();
}
publicActionResultLogin()
{
returnView();
}
}
}
Create a View
Right-click on the Method ?Add View.
We haveCreated a Saved, Not Save and Login Empty View in Authorize Folder.
Login.cshtml
In Views/Authorize/login.cshtml, replace the contents of the file with the following code to replace the text about ASP.NET and MVC with text about this application.
<system.web>
<compilation debug="true" targetframework="4.6.1">
<httpruntime targetframework="4.6.1">
<customerrors mode="On">
<authentication mode="Forms">
<forms loginurl="/Authorize/Login"></forms>
</authentication>
</customerrors></httpruntime></compilation></system.web>
Now Run ActionFilterDemo Project. The Output of Login Page then write a Url in Authorize/Save. Redirect to save Method.It will be display output in Authorize.
Conclusion
This blog depicts about action filters which wraps the action method execution. It is an additional processing, such as providing extra data to the action method, inspecting the return value, or cancelling execution of the action method.
Top comments (0)