Action filter for ASP. net mvc notes

Source: Internet
Author: User

The Action filter is the attribute added to the top of the Action in the Code. The MVC Framework contains some filters, such:
OutputCache-indicates that the Controller caches the returned results within the specified time.
HandleError-handle the exception thrown by Action in contrler
Authorize-Restrict access to actions by a specific user or role
You can also define your own filters, such as: You want to use a custom authentication mechanism, and you want to modify the data returned by the Action.
Use Action Filter
The Action filter can not only control a single Action, but also control the entire contrler. At the same time, an Action can apply multiple filters. For example:

Public class DataController: Controller
{
[OutputCache (Duration = 10)]
Public string Index ()
{
Return DateTime. Now. ToString ("T ");
}
}

This Action returns the current time, but if you refresh the interface within 10 seconds, you will always get the same value becauseOutputCache (Duration = 10).
Filter Type
The ASP. net mvc Framework supports the following filters:
1. Authorization filter-implements the IAuthorizationFilter interface. These filters are used for user authentication and Action Access authorization. For example, Authorize is an Authorization filter.
2. Action filter-implements the IActionFilter interface. It can contain the logic before or after the Action is executed. For example, some filters are used to modify the data returned by the Action.
3. Result filter-implements the IResultFilter interface. It can contain the logic before or after the view result is generated. For example, some filters are used to modify the results before the view is displayed to the browser.
4. Exception filter-implements the IExceptionFilter interface. It is used to handle errors of actions or results, and can also be used to record errors.
The default execution sequence of the filter is the same as that of the list above. For example, the Authorization filter is executed before the Action filter, and the Exception filter is always executed at the end. Of course, you can also set the filter execution sequence through the Order attribute as needed.
Custom Filter
Custom filters must inherit System. Web. Mvc. FilterAttribute and implement one or more of the preceding interfaces. To facilitate developers, the MVC Framework predefines an ActionFilterAttribute class, which implements the IActionFilter and IResultFilter interfaces. You can reload the following methods in the ActionFilterAttribute class:
OnActionExecuting-called before the Action is executed.
OnActionExecuted-called after the Action is executed.
OnResultExecuting-called before the Result is generated.
OnResultExecuted-called before the Result is generated.
The following example shows a class:

Code
Public class LogActionFilter: ActionFilterAttribute
{
Public override void OnActionExecuting (ActionExecutingContext filterContext)
{
Log ("OnActionExecuting", filterContext. RouteData );
}

Public override void OnActionExecuted (ActionExecutedContext filterContext)
{
Log ("OnActionExecuted", filterContext. RouteData );
}

Public override void OnResultExecuting (ResultExecutingContext filterContext)
{
Log ("OnResultExecuting", filterContext. RouteData );
}

Public override void OnResultExecuted (ResultExecutedContext filterContext)
{
Log ("OnResultExecuted", filterContext. RouteData );
}

Private void Log (string methodName, RouteData routeData)
{
Var controllerName = routeData. Values ["controller"];
Var actionName = routeData. Values ["action"];
Var message = String. Format ("{0} controller: {1} action: {2}", methodName, controllerName, actionName );
Debug. WriteLine (message, "Action Filter Log ");
}

}

After you crown LogActionFilter on an Action or Controller, the execution of the corresponding Action is printed. For example:

 

[LogActionFilter]
Public class HomeController: Controller
{}

OutputCache Filter
You can use the OutputCache filter to cache your query results. This improves the user experience and reduces the number of queries. It has the following attributes:
Duration: The cache time, in seconds. Theoretically, the cache time can be very long. However, when the system resources are insufficient, the cache space will still be reclaimed by the system.
VaryByParam: Indicates the field used to cache data. For example, if the "ID" field changes and the cache needs to be changed (the original cache can still be retained), set VaryByParam to "ID ". Here you can set the following values:
* = Cache changes when any parameter changes.
None = the cache is not changed.
Field name list separated by semicolons (;) = the fields in the list change, and the cache is changed.

Location: Where the cached data is stored. The cache location is very important. If there is a server, all users will see the same cache view. If there is a client, users will only see their own cache. For example, some private information cannot exist on the server. You can set the following values:
· Any: the default value. The output cache can be on the browser client that generates the request, the proxy server that participates in the request (or Any other server), or the server that processes the request.

· Client: the output cache is located on the browser Client that generates the request.

· Downstream output cache can be stored on any HTTP 1.1 cacheable device, except for the source server. This includes the proxy server and the client sending the request.

· Server: the output cache is located on the Web Server that processes the request.

· None: the output cache is disabled for the requested page.

· ServerAndClient: the output cache can only be stored on the source server or the client sending the request. The proxy server cannot cache the response.

NoStore: This attribute defines a Boolean value to determine whether to block secondary storage of sensitive information.
In addition to adding attributes directly before the Action or class definition, you can also use the configuration file to dynamically configure your cache mode.
In the <system. web> section, add the following Configuration:

<Caching>
<OutputCacheSettings>
<OutputCacheProfiles>
<Add name = "Cache1Hour" duration = "3600" varyByParam = "none"/>
</OutputCacheProfiles>
</OutputCacheSettings>
</Caching>

You can use the following in Controller:

[OutputCache (CacheProfile = "Cache1Hour")]
Public string Index ()
{
Return DateTime. Now. ToString ("T ");
}

[Extension] Add dynamic content on cached pages
To improve user experience, we use the caching technology, but sometimes we need to change the content on the page, such as providing dynamic information and advertisement changes.
You can callHttpResponse. WriteSubstitution ()Method.
For example:

 

<% Response. WriteSubstitution (News. RenderNews); %>

Here, News. RenderNews is a static method, which is defined as follows. This method is used to randomly display three ad words.

Code
Public class News
{
Public static string RenderNews (HttpContext context)
{
Var news = new List <string>
{
"Gas prices go up! ",
"Life discovered on Mars! ",
"Moon disappears! "
};

Var rnd = new Random ();
Return news [rnd. Next (news. Count)];
}

}

You can even extend a Helper method for the Response. WriteSubstitution () method, as shown below:

Code
Public static class AdHelper
{
Public static void RenderBanner (this HtmlHelper helper)
{
Var context = helper. ViewContext. HttpContext;
Context. Response. WriteSubstitution (RenderBannerInternal );
}

Private static string RenderBannerInternal (HttpContext context)
{
Var ads = new List <string>
{
"/Ads/banner1.gif ",
"/Ads/banner2.gif ",
"/Ads/banner3.gif"
};

Var rnd = new Random ();
Var ad = ads [rnd. Next (ads. Count)];
Return String. Format ("}

}

Then you can call the following code on the page:

<% Html. RenderBanner (); %>

In this way, the page is refreshed and the image is changed once. However, the data content is still cached, and the database will not be queried again because you have refreshed the page.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.