Search code examples
.net-6.0feature-flags

.NET Core 6 Feature Flag Custom Filter with IContextualFeatureFilter not Evaluating


Using .NET Core 6, I am trying to use FeatureManager but when I build a Custom Filter with my own context, the filter does not evaluate and IsEnabledAsync always returns false. No errors or exceptions are thrown. I have verified that simple On/Off feature flags work as expected such as:

"FeatureManagement": {
  "ShowLearningGoalsToCourseDirectors": true    
}

This is the code in the appsettings.json

"FeatureManagement": {
  "ShowLearningGoalsToCourseDirectors": {
    "EnabledFor": {
      "Name": "PhaseFilter",
      "Parameters": {
        "AllowedPhases": "FCC"
      }
    }
  }
}

This is my current implementation of the custom filter. I am not currently concerned how the filter is evaluated, hence it is just checking if the phases string length passed in is greater than 0

[FilterAlias("PhaseFilter")]
public class PhaseFilter : IContextualFeatureFilter<PhaseContext>
{

    public Task<bool> EvaluateAsync(FeatureFilterEvaluationContext featureFilterContext, PhaseContext phaseContext)
{
    var allowedPhases = featureFilterContext.Parameters.GetSection("AllowedPhases").Value;

    var phases = phaseContext.Phases;

    if(phases.Length > 0)
    {
        return Task.FromResult(true);
    }
    else
    {
        return Task.FromResult(false);
    }
}

public class PhaseContext
{
    public string Phases { get; set; }
}

public class PhaseFilterSettings
{
    public string AllowedPhases { get; set; }
}

Finally, this is my registration on the Startup.cs in the ConfigureServices method

services.AddFeatureManagement().AddFeatureFilter<PhaseFilter>();

I am trying to evaluate the feature flag with the filter in this way

string phases = "test";
bool isEnabled = await _featureManager.IsEnabledAsync("ShowLearningGoalsToCourseDirectors", new PhaseContext() { Phases = phases });

Solution

  • The issue was actually on the syntax of the definition of the filter on the .json file. Enabled for is an array so instead of using {} I needed to be using []. This worked.

    "FeatureManagement": {
      "ShowLearningGoalsToCourseDirectors": {
        "EnabledFor": [
          "Name": "PhaseFilter",
          "Parameters": {
            "AllowedPhases": "FCC"
          }
        ]
      }
    }