The goal of this tutorial is to explain action filters. 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 executed. The ASP.NET MVC framework includes several action filters:
- OutputCache – This action filter caches the output of a controller action for a specified amount of time.
- HandleError – This action filter handles errors raised when a controller action executes.
- Authorize – This action filter enables you to restrict access to a particular user or role.
You also can create your own custom action filters. For example, you might want to create a custom action filter in order to implement a custom authentication system. Or, you might want to create an action filter that modifies the view data returned by a controller action.
In this tutorial, you learn how to build an action filter from the ground up. We create a Log action filter that logs different stages of the processing of an action to the Visual Studio Output window..Using an Action Filter
An action filter is an attribute. You can apply most action filters to either an individual controller action or an entire controller.
For example, the Data controller in Listing 1 exposes an action named
Index()
that returns the current time. This action is decorated with the OutputCache
action filter. This filter causes the value returned by the action to be cached for 10 seconds.using System; using System.Web.Mvc; namespace MvcApplication1.Controllers { public class DataController : Controller { [OutputCache(Duration=10)] public string Index() { return DateTime.Now.ToString("T"); } } }
No comments:
Post a Comment