How to: Create an Action Filter in Visual Studio

Introduction

An action filter consists of logic that runs directly before or directly after an action method runs. You can use action filters for logging, authentication, output caching, or other uses.

You implement an action filter as an attribute that inherits from the ActionFilterAttribute class. You can override the OnActionExecuting method if you want your logic to run before the action method. Or you can override the OnActionExecuted method if you want your logic to run after the action method. After you define an action filter, you can use the attribute to mark any action methods that you want the filter to apply to.

This topic describes how to create an action filter and use the attribute to mark one or more action methods.

To create an action filter

  1. In Visual Studio, open the MVC application project to which you want to add the action filter.

  2. In Solution Explorer, right-click the Controllers folder, click Add, and then click New Item.

    The Add New Item dialog box is displayed.

  3. Under Templates, select the Class template.

  4. In Name, type the name of the new action filter attribute class.

    Note

    By convention, the name of your action filter attribute should end with "Attribute", such as LogFilterAttribute or OutputFilterAttribute.

  5. Click Add.

    The class is added to your project.

  6. Open the new class and add code so that it inherits from the ActionFilterAttribute class, as shown in the following example:

    Public Class CachingFilterAttribute
        Inherits ActionFilterAttribute

    public class CachingFilterAttribute : ActionFilterAttribute
  7. If you want the filter to run directly before an action method, override the OnActionExecuting method and add your logic.

    The following example shows a skeleton OnActionExecuting method.

    Public Overrides Sub OnActionExecuting(ByVal filterContext As _
            ActionExecutingContext)
        ' The action filter logic.
    End Sub

    public override void OnActionExecuting(ActionExecutingContext 
            filterContext)
    {
        // The action filter logic.
    }
  8. If you want the filter to run directly after an action method, override the OnActionExecuted method and add your logic.

    The following example shows a skeleton OnActionExecuted method.

    Public Overrides Sub OnActionExecuted(ByVal filterContext As _
            ActionExecutedContext)
        ' The action filter logic.
    End Sub

    public override void OnActionExecuted(ActionExecutedContext 
            filterContext)
    {
        // The action filter logic.
    }
  9. In controller classes, add the filter attribute to any action method that you want the filter to apply to.

    The following example shows an Index action method that has been marked with the CachingFilter action filter.

    <CachingFilter()> _
    Public Function Index()
        ' The action method logic.
    End Function

    [CachingFilter]
    public ActionResult Index()
    {
        // The action method logic.
    }

Example

The following example shows an action filter that overrides both the OnActionExecuting and OnActionExecuted methods.

Public Class LoggingFilterAttribute
    Inherits ActionFilterAttribute
    Public Overrides Sub OnActionExecuting(ByVal filterContext As _
            ActionExecutingContext)
        filterContext.HttpContext.Trace.Write("Starting: " + _
                filterContext.ActionMethod.Name)

        MyBase.OnActionExecuting(filterContext)
    End Sub

    Public Overrides Sub OnActionExecuted(ByVal filterContext As _
            ActionExecutedContext)
        If Not filterContext.Exception Is Nothing Then
            filterContext.HttpContext.Trace.Write("Exception thrown")
        End If

        MyBase.OnActionExecuted(filterContext)
    End Sub
End Class
[C#]
public class LoggingFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext 
         filterContext)
    {
        filterContext.HttpContext.Trace.Write("Starting: " +
            filterContext.ActionMethod.Name);

        base.OnActionExecuting(filterContext);
    }

    public override void OnActionExecuted(ActionExecutedContext 
         filterContext)
    {
        if (filterContext.Exception != null)
            filterContext.HttpContext.Trace.Write("Exception thrown");

        base.OnActionExecuted(filterContext);
    }
}

Example

The following example shows an MVC controller with action methods that are marked with the LoggingFilter attribute from the previous example.

Public Class HomeController
        Inherits Controller
    <LoggingFilter()> _
    Public Function Index()
        ViewData("Title") = "Home Page"
        ViewData("Message") = "Welcome to ASP.NET MVC!"

        Return RenderView()
    End Function

    <LoggingFilter()> _
    Public Function About()
        ViewData("Title") = "About Page"

        Return RenderView()
    End Function
End Class
public class HomeController : Controller
{
    [LoggingFilter]
    public ActionResult Index()
    {
        ViewData["Title"] = "Home Page";
        ViewData["Message"] = "Welcome to ASP.NET MVC!";

        return RenderView();
    }

    [LoggingFilter]
    public ActionResult About()
    {
        ViewData["Title"] = "About Page";

        return RenderView();
    }
}

See Also

This topic is ASP.NET Extensions documentation and is unsupported by Microsoft. Blank topics are included as placeholders and existing content is subject to change in future releases.