Click here to Skip to main content
15,868,016 members
Articles / Programming Languages / C#

FluentFilters for ASP.NET Core

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
15 Jul 2016CPOL2 min read 17.1K   8  
In this article, a library for ASP.NET Core, that will add support of criteria for global action filters.

Few years ago I have implemented the library for ASP.NET MVC, that can be used as a facility for registering global filters in ASP.NET MVC 2 and add support of criteria for global filters in ASP.NET MVC 3. Nowadays Microsoft working over the new version of their web framework and I decided to customize my library for this release. So, let's see what is it and how to use it.

ASP.NET Core have ability to register filters globally. It's works great, but sometimes it would be nice to specify conditions for filter execution and FluentFlters will help with this task.

Project on GitHub: https://github.com/banguit/fluentfilters

Install package

For ASP.NET Core Web Application you should use FluentFilter version 0.3.* and higher. Currently the latest version 0.3.0.
To install the latest package you can use Nuget Package Manager in Visual Studio or specify dependency in project.json file as shown below and call for package restore.

<code>{
    //...

    "dependencies": {

        //...
        "FluentFilters": "0.3.0"
    },

    //...
}    
</code>

Configuration:

After installing the package to your ASP.NET Core Web Application you should replace default filter provider by custom from library. Your Startup class should looks like shown below:

<code>// Startup.cs
using FluentFilters;  
using FluentFilters.Criteria;

namespace DotNetCoreWebApp  
{
  public class Startup
  {
    //...
    public void ConfigureServices(IServiceCollection services)
    {
      //...
      services.AddMvc(option =>
      {
        option.Filters.Add(new AddHeaderAttribute("Hello", "World"), c =>
        {
          // Example of using predefined FluentFilters criteria
          c.Require(new ActionFilterCriteria("About"))
            .Or(new ControllerFilterCriteria("Account"))
            .And(new ActionFilterCriteria("Login"));
        });
      });

      // Replace default filter provider by custom from FluentFilters library
      Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.Replace(services, ServiceDescriptor.Singleton<IFilterProvider, FluentFilterFilterProvider>());
      //...
    }
    //...
  }
}
</code>

Registering filters

To register filters with criteria, you need do it in usual way but calling extended methods Add or AddService. Below you can see signature of these methods.

<code>// Register filter by instance
void Add(this FilterCollection collection, IFilterMetadata filter, Action<IFilterCriteriaBuilder> criteria);

// Register filter by type
IFilterMetadata Add(this FilterCollection collection, Type filterType, Action<IFilterCriteriaBuilder> criteria)  
IFilterMetadata Add(this FilterCollection collection, Type filterType, int order, Action<IFilterCriteriaBuilder> criteria)  
IFilterMetadata AddService(this FilterCollection collection, Type filterType, Action<IFilterCriteriaBuilder> criteria)  
IFilterMetadata AddService(this FilterCollection collection, Type filterType, int order, Action<IFilterCriteriaBuilder> criteria)  
</code>

Specify conditions

To specify the conditions, you should set the chain of criteria for the filter at registration. Using criteria, you can set whether to execute a filter or not. The library already provides three criteria for use:

  • ActionFilterCriteria - filter by specified action
  • AreaFilterCriteria - filter by specified area
  • ControllerFilterCriteria - filter by specified controller

For one filter, you can only specify two chains of criteria. These are the chains of criteria that are required and which should be excluded.

<code>option.Filters.Add(typeof(CheckAuthenticationAttribute), c =>  
{
    // Execute if current area "Blog"
    c.Require(new AreaFilterCriteria("Blog"));
    // But ignore if current controller "Account"
    c.Exclude(new ControllerFilterCriteria("Account"));
});
</code>

Chains of criteria are constructed by using the methods And(IFilterCriteria criteria) and Or(IFilterCriteria criteria), which work as conditional logical operators && and ||.

<code>option.Filters.Add(typeof(DisplayTopBannerFilterAttribute), c =>  
{
    c.Require(new IsFreeAccountFilterCriteria())
        .Or(new AreaFilterCriteria("Blog"))
        .Or(new AreaFilterCriteria("Forum"))
            .And(new IsMemberFilterCriteria());

    c.Exclude(new AreaFilterCriteria("Administrator"))
        .Or(new ControllerFilterCriteria("Account"))
            .And(new ActionFilterCriteria("LogOn"));
});
</code>

If using the C# language, then the code above can be understood as (like pseudocode):

<code>if( IsFreeAccountFilterCriteria() || area == "Blog" ||  
    (area == "Forum" && IsMemberFilterCriteria()) ) 
{
    if(area != "Administrator")
    {
        DisplayTopBannerFilter();
    }
    else if(controller != "Account" && action != "LogOn")
    {
        DisplayTopBannerFilter();
    }
}
</code>

Implementation of custom criteria

To create a custom criterion you should inherit your class from the FluentFilters.IFilterCriteria interface and implement only one method Match with logic to making decision about filter execution. As example, look to the source code for ActionFilterCriteria:

<code>public class ActionFilterCriteria : IFilterCriteria  
{
    #region Fields

    private readonly string _actionName;

    #endregion

    #region Constructor

    /// <summary>
    /// Filter by specified action
    /// </summary>
    /// <param name="actionName">Name of the action</param>
    public ActionFilterCriteria(string actionName)
    {
        _actionName = actionName;
    }

    #endregion

    #region Implementation of IActionFilterCriteria

    public bool Match(FilterProviderContext context)
    {
        return string.Equals(_actionName, context.ActionContext.RouteData.GetRequiredString("action"), StringComparison.OrdinalIgnoreCase);
    }

    #endregion
}
</code>

If you are looking for FluentFilters for ASP.NET MVC2/3, you can find it here.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Warner Bros Discovery
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --