Exercise 1: Creating a Global Action Filter

In this exercise, you will learn how to add a global filter that will perform certain logic before displaying each view. In order to do that, you will register as global the custom filter for application logging created in ASP.NET MVC Custom Action Filter Hands-on Lab.

Task 1 – Registering a Filter as Global

In this task, you will register a global filter to manage your site logging at a global level. In order to do that, you will add ActionLogFilterAttribute filter into MVC GlobalFilterCollection at Global.asax.[cs|vb].

  1. Open the begin solution MvcMusicStore.sln at Source\Ex01-Global Action Filter\Begin.
  2. Open Global.asax.[cs|vb] at project root. In the method RegisterGlobalFilters , add a new security filter to the filters collection:


    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    FakePre-5f38acb2a4564f0292c8d2f96efd8aeb-eb1b64a4b5f34015af668a390dee9bd4FakePre-7cd5eff99dfe482b89514ef8cf229955-d68c9208a77e47baaf90ab2a82c1404a filters.Add(new ActionLogFilterAttribute());FakePre-1c3ff166ca4d4351aac953b353607df0-be3c953302ea42b1ba22b1d90459098f

    Visual Basic

    Public Shared Sub RegisterGlobalFilters(ByVal filters As GlobalFilterCollection) 
    FakePre-6fd01d21c44349e49db406237f409f91-ee37140ad70a405db37ca07df0a20568 filters.Add(New ActionLogFilterAttribute) FakePre-b4c6847b59d64ed39dd5f6bfed6dff2f-45550272338041ac9a9035f08cf5f6e4

    the previous implementation of RegisterGlobalFilters (with the HandleErrorAttribute filter only) is the one included in an MVC 3 application by default. In this task, you are only adding an additional filter, ActionLogFilterAttribute.

Task 2 – Running the Application

  1. Press F5 to run the application.
  2. Browse to /ActionLog View. You will see that the initial activities have been tracked.

    Figure 1

    ActionLogView: Initial site activity was tracked

  3. Click on Admin to load the LogOn View.
  4. Browse /ActionLog view again to see the administration site tracked. If you see the same table as before, please refresh the page.

    Figure 2

    ActionLogView: Recent activities logged

Next Step

Exercise 2: Creating a Global Dynamic Filter