Posted by: Cirilo Meggiolaro | 04/24/2009

Tip of the day #192 – ASP.NET MVC – Action Filters

ASP.NET MVC Action filters are basically operations that may be requested either before or just after an action method be executed.

Action filters are defined with attributes that may be applied to either a specific method or a class. If you apply an action filter to a class, all action methods will be affected by the action filters.

Some built-in action filters

Let’s check two action filters available in ASP.NET MVC.

OutputCache: Used to dictate how an action method will be cached. The following properties are available:

  • string CacheProfile: Gets or sets the cache profile;
  • int Duration: Gets or sets the duration;
  • OutputCacheLocation Location: Gets or sets the location;
  • bool NoStore: Gets or sets a value indicating whether to store the cache;
  • string SqlDependency: Gets or sets the SQL dependency;
  • string VaryByContentEncoding: Gets or sets the vary by content encoding;
  • string VaryByCustom: Gets or sets the vary by custom;
  • string VaryByHeader: Gets or sets the vary by header;
  • string VaryByParam: Gets or sets the vary by param.

Example:

The following example shows an action method that has the OutputCache attribute defined and is set to refresh every 10 seconds.

[OutputCache(Duration=10,VaryByParam=“”)]
public ActionResult Index()
{
    ViewData[“CurrentTime”] = DateTime.Now.ToLongTimeString();
    return View();
}

The VaryByParam property is mandatory but since the action method does not expect any parameter, it is set to empty. Because the output cache attribute makes the method to be bypassed within the cache duration it is useful when you have an action method that expects a parameter and you want to check if the parameter requested has changed or not. Refreshing the page within the 10 seconds will not make the method to be executed again but if the parameter defined on the VaryByParam changes the method will be executed.

[OutputCache(Duration=10,VaryByParam=“productID”)]
public ActionResult Index(int productID)
{
    ViewData[“ProductID”] = productID;
    return View();
}

HandleError: This action filter is responsible for catching exceptions raised within action methods and rendering a default error view. When you create a new ASP.NET MVC web application a view called Error.aspx is added under the Views > Shared folder. The following properties are available:

  • Type ExceptionType: Gets or sets the type of the exception;
  • string Master: Gets or sets the master view;
  • string View: Gets or sets the page view.

Example:

The example below shows an action method that raises an exception. The method has a HandleError attribute applied to it. It means that when the exception is thrown the action filter will try to load the default view (View/Shared/Error.aspx) and display a static message.

[HandleError]
public ActionResult Index()
{
    throw new Exception(“Something goes wrong…”);
}

If you want to specify a different view or a specific exception type, you may define the type on the attribute. The following code snippet shows a method that will load a view called DisplayError if an ArgumentNullException is thrown:

[HandleError(ExceptionType=typeof(ArgumentNullException),View=“DisplayError”)]
public ActionResult Index(string str)
{
    if (string.IsNullOrEmpty(str))
        throw new ArgumentNullException(“str”, “Argument cannot be null”);

    return View();
}

As default the web.config does not contain the customErrors element defined. So don’t forget to define it.

<configuration>
    <system.web>
        <customErrors mode=”On” />
    </system.web>
</configuration>

Tomorrow we are going to check how to create custom action filters.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: