Filter is actually a feature. It provides a method to add certain tasks to the controller or action. When the controller or action is called, the corresponding method defined in the filter is triggered. Filter should be regarded as an implementation method of AOP. For the content of AOP, you can refer to the following illustration to explain it clearly. Therefore, we can use filters to break down horizontal and vertical applications, such as logs, permissions, caches, anti-leeching, and so on.
1. Let's take a look at several default filter types provided by the ASP. net mvc framework:
1. Authorize:
Prerequisites: go to C: \ WINDOWS \ Microsoft. NET \ Framework \ v2.0.50727folder, double-click aspnet_regsql.exe, select the corresponding database, create membership, AuthorizeAttribute use membership for permission verification, so we need to first prepare a user in membership, one role Admin, we use the studio project-ASP.. NET configuration.
[Authorize (Roles = "Admin")]
Public ActionResult Index ()
{
ViewData ["Message"] = "Welcome to ASP. net mvc! ";
Return View ();
}
The Index page cannot be accessed if the system does not belong to the Admin role.
2. OutputCache:
[OutputCache (Duration = 60, VaryByParam = "none")]
Public ActionResult About ()
{
Return View ();
}
Then we modify About to add:
<% = DateTime. Now. ToString () %>
We will find that the output of refreshing the About page within one minute does not change. This is very similar to the page caching mechanism in webform.
You can configure the time and conditions in a unified manner.
Configuration File
<System. web>
<Caching>
<OutputCacheSettings>
<OutputCacheProfiles>
<Add name = "MyProfile" duration = "60" varyByParam = "none"/>
</OutputCacheProfiles>
</OutputCacheSettings>
</Caching>
</System. web>
Input in Controler
[OutputCache (CacheProfile = "MyProfile")]
Public ActionResult About ()
{
Return View ();
}
3. Exception
Exception
[HandleError (ExceptionType = typeof (ArgumentException), View = "Error")]
Public ActionResult GetProduct (string name)
{
If (name = null)
{
Throw new ArgumentNullException ("name blank ");
}
Return View ();
}
The Action marked with the HandleError attribute jumps to the corresponding View based on the exception type when an internal exception occurs. Note that the above source code cannot see the effect during development, you must deploy it on iis to see the effect. In fact, this simple processing is not very useful in projects. Generally, we will write our own exception handling methods. We will explain how to process custom exceptions in a custom filter later.
- Three pages in total:
- Previous Page
- 1
- 2
- 3
- Next Page