Skip to content

Instantly share code, notes, and snippets.

@doeringp
Last active March 20, 2023 22:37
Show Gist options
  • Save doeringp/82d001f03b26a0f0c1c1b473e507244a to your computer and use it in GitHub Desktop.
Save doeringp/82d001f03b26a0f0c1c1b473e507244a to your computer and use it in GitHub Desktop.
ASP.NET Core Feature Flags for SPAs

ASP.NET Core Feature Flags for SPAs

This sample uses https://github.com/microsoft/FeatureManagement-Dotnet for Feature Management in an ASP.NET Core Web API. If you have a JavaScript Single-Page-Application (SPA) as frontend you may want to reuse the feature flags from the backend in the frontend. You can solve this by creating an API Controller that returns all features (enabled or not) as JSON.

GET /features

Response:

{
  "featureA": true,
  "featureB": false
}
{
"FeatureManagement": {
"featureA": true,
"featureB": false
}
}
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.FeatureManagement.AspNetCore" Version="2.4.0" />
<PackageReference Include="System.Linq.Async" Version="5.1.0" />
</ItemGroup>
</Project>
using Microsoft.AspNetCore.Mvc;
using Microsoft.FeatureManagement;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
public class FeaturesController : ControllerBase
{
private readonly IFeatureManager _featureManager;
public FeaturesController(IFeatureManager featureManager)
{
_featureManager = featureManager;
}
[HttpGet("features")]
public async Task<Dictionary<string, bool>> ListFeatures()
{
return await _featureManager.GetFeatureNamesAsync()
.ToDictionaryAsync(
feature => feature,
feature => _featureManager.IsEnabledAsync(feature).GetAwaiter().GetResult());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment