Hướng dẫn custom filter trong mvc 5 năm 2024
Đối với áp dụng cho tất cả các action trong một controller, bạn có thể thêm [CustomActionFilter] trực tiếp lên đầu controller: Show [CustomActionFilter] public class MyController : Controller { }4. Đối với áp dụng cho một action, bạn có thể thêm [CustomActionFilter] trực tiếp lên đầu action: public class MyController : Controller { }Lưu ý rằng để sử dụng filter, bạn cần phải bật tính năng filter trong ứng dụng của mình bằng cách thêm đoạn code sau vào phương thức RegisterGlobalFilters trong file Global.asax.cs: Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support. ASP.NET MVC 4 Custom Action Filters
In this articleBy Web Camps Team Download Web Camps Training Kit ASP.NET MVC provides Action Filters for executing filtering logic either before or after an action method is called. Action Filters are custom attributes that provide declarative means to add pre-action and post-action behavior to the controller's action methods. In this Hands-on Lab you will create a custom action filter attribute into MvcMusicStore solution to catch controller's requests and log the activity of a site into a database table. You will be able to add your logging filter by injection to any controller or action. Finally, you will see the log view that shows the list of visitors. This Hands-on Lab assumes you have basic knowledge of ASP.NET MVC. If you have not used ASP.NET MVC before, we recommend you to go over ASP.NET MVC 4 Fundamentals Hands-on Lab. ObjectivesIn this Hands-On Lab, you will learn how to:
PrerequisitesYou must have the following items to complete this lab:
SetupInstalling Code Snippets For convenience, much of the code you will be managing along this lab is available as Visual Studio code snippets. To install the code snippets run .\Source\Setup\CodeSnippets.vsi file. If you are not familiar with the Visual Studio Code Snippets, and want to learn how to use them, you can refer to the appendix from this document "". ExercisesThis Hands-On Lab is comprised by the following exercises: Estimated time to complete this lab: 30 minutes. Note Each exercise is accompanied by an End folder containing the resulting solution you should obtain after completing the exercises. You can use this solution as a guide if you need additional help working through the exercises. Exercise 1: Logging ActionsIn this exercise, you will learn how to create a custom action log filter by using ASP.NET MVC 4 Filter Providers. For that purpose you will apply a logging filter to the MusicStore site that will record all the activities in the selected controllers. The filter will extend ActionFilterAttributeClass and override OnActionExecuting method to catch each request and then perform the logging actions. The context information about HTTP requests, executing methods, results and parameters will be provided by ASP.NET MVC ActionExecutingContext class . Note ASP.NET MVC 4 also has default filters providers you can use without creating a custom filter. ASP.NET MVC 4 provides the following types of filters:
For more information about Filters Providers please visit this MSDN link: (https://msdn.microsoft.com/library/dd410209.aspx) . About MVC Music Store Application logging featureThis Music Store solution has a new data model table for site logging, ActionLog, with the following fields: Name of the controller that received a request, Called action, Client IP and Time stamp. Data model - ActionLog table The solution provides an ASP.NET MVC View for the Action log that can be found at MvcMusicStores/Views/ActionLog: Action Log view With this given structure, all the work will be focused on interrupting controller's request and performing the logging by using custom filtering. Task 1 - Creating a Custom Filter to Catch a Controller's RequestIn this task you will create a custom filter attribute class that will contain the logging logic. For that purpose you will extend ASP.NET MVC ActionFilterAttribute Class and implement the interface IActionFilter. Note The ActionFilterAttribute is the base class for all the attribute filters. It provides the following methods to execute a specific logic after and before controller action's execution:
By overriding any of these methods into a derived class, you can execute your own filtering code.
Task 2 - Injecting a Code Interceptor into the Store Controller ClassIn this task you will add the custom filter by injecting it to all controller classes and controller actions that will be logged. For the purpose of this exercise, the Store Controller class will have a log. The method OnActionExecuting from ActionLogFilterAttribute custom filter runs when an injected element is called. It is also possible to intercept a specific controller method.
Task 3 - Running the ApplicationIn this task, you will test that the logging filter is working. You will start the application and visit the store, and then you will check logged activities.
Exercise 2: Managing Multiple Action FiltersIn this exercise you will add a second Custom Action Filter to the StoreController class and define the specific order in which both filters will be executed. Then you will update the code to register the filter Globally. There are different options to take into account when defining the Filters' execution order. For example, the Order property and the Filters' scope: You can define a Scope for each of the Filters, for example, you could scope all the Action Filters to run within the Controller Scope, and all Authorization Filters to run in Global scope. The scopes have a defined execution order. Additionally, each action filter has an Order property which is used to determine the execution order in the scope of the filter. For more information about Custom Action Filters execution order, please visit this MSDN article: (https://msdn.microsoft.com/library/dd381609(v=vs.98).aspx). Task 1: Creating a new Custom Action FilterIn this task, you will create a new Custom Action Filter to inject into the StoreController class, learning how to manage the execution order of the filters.
Task 2: Injecting a new Code Interceptor into the StoreController ClassIn this task, you will add a new custom filter into the StoreController Class and run the solution to verify how both filters work together.
Task 3: Managing Filter OrderingIn this task, you will learn how to manage the filters' execution order by using the Order property.
Task 4: Registering Filters GloballyIn this task, you will update the solution to register the new filter (MyNewCustomActionFilter) as a global filter. By doing this, it will be triggered by all the actions performed in the application and not only in the StoreController ones as in the previous task.
SummaryBy completing this Hands-On Lab you have learned how to extend an action filter to execute custom actions. You have also learned how to inject any filter to your page controllers. The following concepts were used:
Appendix A: Installing Visual Studio Express 2012 for WebYou can install Microsoft Visual Studio Express 2012 for Web or another "Express" version using the Microsoft Web Platform Installer. The following instructions guide you through the steps required to install Visual studio Express 2012 for Web using Microsoft Web Platform Installer.
Appendix B: Publishing an ASP.NET MVC 4 Application using Web DeployThis appendix will show you how to create a new web site from the Windows Azure Management Portal and publish the application you obtained by following the lab, taking advantage of the Web Deploy publishing feature provided by Windows Azure. Task 1 - Creating a New Web Site from the Windows Azure Portal
Task 2 - Configuring the Database ServerIf your application makes use of SQL Server databases you will need to create a SQL Database server. If you want to deploy a simple application that does not use SQL Server you might skip this task.
Task 3 - Publishing an ASP.NET MVC 4 Application using Web Deploy
Appendix C: Using Code SnippetsWith code snippets, you have all the code you need at your fingertips. The lab document will tell you exactly when you can use them, as shown in the following figure. Using Visual Studio code snippets to insert code into your project To add a code snippet using the mouse (C#, Visual Basic and XML) 1. Right-click where you want to insert the code snippet. |