Search code examples
blazorblazor-server-sideazure-app-configuration

How do I use Feature Tags from Azure App Config in Blazor?


I am attempting to use feature flags from Azure App Config in my Blazor application. I have been following this documentation from Microsoft to add them. I am successfully able to use them by injecting the FeatureManager into my code sections and utililzing the feature tag in .cshtml files like so,

<feature name="Beta">
    <li class="nav-item">
        <a class="nav-link text-dark" asp-area="" asp-controller="Beta" asp-action="Index">Beta</a>
    </li>
</feature>

However, I have not been able to successfully use the feature tag in my .razor files. This comes as a result of not being able to add this directive to my files.

@addTagHelper *, Microsoft.FeatureManagement.AspNetCore

Is there a way to use the feature tag in my Razor files?


Solution

  • AFAIK Blazor does not yet have a similar component/tag-helper. But not to worry - it's quite easy to check the flags manually.

    @using Microsoft.FeatureManagement
    @inject IFeatureManager FeatureManager
    
    @if (betaFeatureIsEnabled)
    {
        <h1>My Beta Feature</h1>
    }
    
    @code {
        private bool betaFeatureIsEnabled = false;
    
        protected override async Task OnInitializedAsync()
        {
            betaFeatureIsEnabled = await FeatureManager.IsEnabledAsync("Beta");
        }
    }
    

    From this we can roll our own little helper component to make this look quite neat.

    FeatureFlagView.razor (helper component)

    @using Microsoft.FeatureManagement
    @inject IFeatureManager FeatureManager
    
    @if (featureIsEnabled)
    {
        @ChildContent
    }
    
    @code {
        private bool featureIsEnabled = false;
    
        [Parameter] public RenderFragment ChildContent { get; set; }
        [Parameter] public string FlagName { get; set; }
    
        protected override async Task OnInitializedAsync()
        {
            if (string.IsNullOrEmpty(FlagName)) return;
            featureIsEnabled = await FeatureManager.IsEnabledAsync(FlagName);
        }
    }
    
    

    Using the FeatureFlagView inside a .razor page/component

    <FeatureFlagView FlagName="Beta">
        <h1>My Beta Feature</h1>
    </FeatureFlagView>
    

    This could then be extended quite a bit to handle more complex scenarios like requiring multiple flags, not flags etc and more importantly using Enum's (instead of strings).