mcpField
F
feature-flags

feature-flags

github.com/wshaddix开发8671 次安装36 周前更新
代码仓库

关于 feature-flags

面向 Razor Pages 应用开发者的功能标志模式技能,介绍如何配置和检查功能开关。内容涉及页面控制、用户或比例定向发布,以及按时间启用功能。

主要功能

  1. 01基于配置的功能标志
  2. 02强类型标志定义
  3. 03Razor Pages 条件渲染与路由
  4. 04页面和控制器功能门控
  5. 05用户与比例定向发布
  6. 06基于时间窗口的启用

适用场景

  1. 01按环境切换应用功能
  2. 02限制页面或控制器的访问
  3. 03向特定用户群逐步发布功能
  4. 04在维护或活动时段启用功能

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/wshaddix/dotnet-skills --skill feature-flags

安装后在 Claude Code 中输入/feature-flags确认已加载。

详细介绍

原理

功能标志可实现安全部署、渐进式发布、A/B 测试和快速回滚。如果缺少合适的功能标志模式,团队就可能部署未完成的功能,或无法快速响应生产环境问题。这些模式为 Razor Pages 应用程序提供了一种稳健、易维护的功能管理方法。

模式

模式 1:基于配置的功能标志

使用 appsettings.json 配置简单的功能开关,并针对不同环境进行覆盖。

// appsettings.json
{
  "FeatureManagement": {
    "NewDashboard": false,
    "BetaFeature": false,
    "DarkMode": true,
    "PaymentV2": {
      "EnabledFor": [
        {
          "Name": "Microsoft.Targeting",
          "Parameters": {
            "Audience": {
              "Users": [ "[email protected]" ],
              "Groups": [ "BetaTesters" ],
              "DefaultRolloutPercentage": 0
            }
          }
        }
      ]
    }
  }
}

// appsettings.Production.json
{
  "FeatureManagement": {
    "NewDashboard": true,
    "PaymentV2": {
      "EnabledFor": [
        {
          "Name": "Microsoft.Targeting",
          "Parameters": {
            "Audience": {
              "Users": [ "[email protected]" ],
              "Groups": [ "BetaTesters" ],
              "DefaultRolloutPercentage": 25
            }
          }
        }
      ]
    }
  }
}
// Program.cs - Basic setup
builder.Services.AddFeatureManagement();

// With custom configuration section
builder.Services.AddFeatureManagement(
    builder.Configuration.GetSection("FeatureManagement"));

// With feature filters
builder.Services.AddFeatureManagement()
    .AddFeatureFilter<TargetingFilter>()
    .AddFeatureFilter<PercentageFilter>()
    .AddFeatureFilter<TimeWindowFilter>();
模式 2:强类型功能标志

创建强类型功能标志,以确保编译时安全性并提高可发现性。

// Feature flag constants
public static class FeatureFlags
{
    public const string NewDashboard = "NewDashboard";
    public const string BetaFeature = "BetaFeature";
    public const string DarkMode = "DarkMode";
    public const string PaymentV2 = "PaymentV2";
    public const string ApiRateLimiting = "ApiRateLimiting";
    public const string AdvancedReporting = "AdvancedReporting";
}

// Feature-aware service interface
public interface IFeatureAwareService
{
    Task<bool> IsEnabledAsync(string featureName);
    Task<bool> IsEnabledAsync<TContext>(string featureName, TContext context);
}

public class FeatureService : IFeatureAwareService
{
    private readonly IFeatureManager _featureManager;

    public FeatureService(IFeatureManager featureManager)
    {
        _featureManager = featureManager;
    }

    public Task<bool> IsEnabledAsync(string featureName) =>
        _featureManager.IsEnabledAsync(featureName);

    public Task<bool> IsEnabledAsync<TContext>(string featureName, TContext context) =>
        _featureManager.IsEnabledAsync(featureName, context);
}

// Extension methods for easier usage
public static class FeatureManagerExtensions
{
    public static Task<bool> IsNewDashboardEnabledAsync(this IFeatureManager manager) =>
        manager.IsEnabledAsync(FeatureFlags.NewDashboard);

    public static Task<bool> IsPaymentV2EnabledAsync(this IFeatureManager manager, string userId) =>
        manager.IsEnabledAsync(FeatureFlags.PaymentV2, new TargetingContext { UserId = userId });
}
模式 3:Razor Pages 集成

在 Razor Pages 中使用功能标志,实现有条件的 UI 渲染和路由。

// PageModel with feature flag checks
public class DashboardModel : PageModel
{
    private readonly IFeatureManager _featureManager;

    public DashboardModel(IFeatureManager featureManager)
    {
        _featureManager = featureManager;
    }

    public bool UseNewDashboard { get; private set; }
    public bool IsDarkModeEnabled { get; private set; }

    public async Task OnGetAsync()
    {
        UseNewDashboard = await _featureManager.IsEnabledAsync(FeatureFlags.NewDashboard);
        IsDarkModeEnabled = await _featureManager.IsEnabledAsync(FeatureFlags.DarkMode);
    }
}

// View with conditional rendering
@page
@model DashboardModel
@inject IFeatureManager FeatureManager

@if (Model.UseNewDashboard)
{
    <partial name="_NewDashboard" model="Model" />
}
else
{
    <partial name="_LegacyDashboard" model="Model" />
}

@if (await FeatureManager.IsEnabledAsync(FeatureFlags.BetaFeature))
{
    <div class="alert alert-info">
        <strong>Beta:</strong> Try our new experimental features!
    </div>
}

@if (Model.IsDarkModeEnabled)
{
    <button id="theme-toggle" class="btn btn-outline-secondary">
        Toggle Dark Mode
    </button>
}
模式 4:功能门控操作筛选器

使用内置的功能门控筛选器,对控制器或页面级别的功能进行控制。

// Controller/PageModel level feature gate
[FeatureGate(FeatureFlags.BetaFeature)]
public class BetaFeaturesModel : PageModel
{
    public void OnGet()
    {
        // This page is only accessible when BetaFeature is enabled
    }
}

// Alternative: Redirect to different page
[FeatureGate(FeatureFlags.NewDashboard, 
    RequirementType.All,  // All features must be enabled
    NoFeatureRedirect = "/Dashboard/Legacy")]
public class NewDashboardModel : PageModel
{
    // Redirects to legacy dashboard if NewDashboard is disabled
}

// Custom feature gate attribute for complex scenarios
public class PremiumFeatureAttribute : FeatureGateAttribute
{
    public PremiumFeatureAttribute() 
        : base(FeatureFlags.AdvancedReporting)
    {
    }
}

[PremiumFeature]
public class ReportsModel : PageModel
{
    // Premium feature page
}
模式 5:基于目标的渐进式发布

安全地实现基于用户和基于百分比的渐进式发布。

// Custom targeting context
public class FeatureTargetingContext : ITargetingContext
{
    public string? UserId { get; set; }
    public List<string> Groups { get; set; } = new();
}

// Targeting context accessor
public class HttpContextTargetingContextAccessor : ITargetingContextAccessor
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public HttpContextTargetingContextAccessor(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public ValueTask<TargetingContext> GetContextAsync()
    {
        var httpContext = _httpContextAccessor.HttpContext;
        
        if (httpContext?.User?.Identity?.IsAuthenticated != true)
        {
            return ValueTask.FromResult(new TargetingContext());
        }

        var context = new TargetingContext
        {
            UserId = httpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value,
            Groups = httpContext.User.FindAll(ClaimTypes.Role)
                .Select(c => c.Value)
                .ToList()
        };

        return ValueTask.FromResult(context);
    }
}

// Registration
builder.Services.AddHttpContextAccessor();
builder.Services.AddSingleton<ITargetingContextAccessor, HttpContextTargetingContextAccessor>();
builder.Services.AddFeatureManagement()
    .AddFeatureFilter<TargetingFilter>();

// Usage in PageModel
public class CheckoutModel : PageModel
{
    private readonly IFeatureManager _featureManager;

    public CheckoutModel(IFeatureManager featureManager)
    {
        _featureManager = featureManager;
    }

    public async Task<IActionResult> OnPostAsync()
    {
        var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "anonymous";
        
        if (await _featureManager.IsEnabledAsync(FeatureFlags.PaymentV2, new 
        {
            UserId = userId,
            Groups = User.FindAll(ClaimTypes.Role).Select(c => c.Value).ToList()
        }))
        {
            return await ProcessPaymentV2Async();
        }

        return await ProcessLegacyPaymentAsync();
    }
}
模式 6:基于时间的功能标志

在特定时间段内自动启用功能。

{
  "FeatureManagement": {
    "HolidayTheme": {
      "EnabledFor": [
        {
          "Name": "Microsoft.TimeWindow",
          "Parameters": {
            "Start": "2024-12-01T00:00:00Z",
            "End": "2025-01-02T00:00:00Z"
          }
        }
      ]
    },
    "MaintenanceMode": {
      "EnabledFor": [
        {
          "Name": "Microsoft.TimeWindow",
          "Parameters": {
            "Start": "2024-12-25T02:00:00Z",
            "End": "2024-12-25T04:00:00Z"
          }
        }
      ]
    }
  }
}
// Time window filter usage
[FeatureGate(FeatureFlags.MaintenanceMode)]
public class MaintenanceModel : PageModel
{
    public IActionResult OnGet()
    {
        // Show maintenance page only during window
        return Page();
    }
}

// Custom time-based filter for recurring schedules
public class RecurringTimeFilter : IFeatureFilter
{
    public Task<bool> EvaluateAsync(FeatureFilterEvaluationContext context)
    {
        var settings = context.Parameters.Get<RecurringTimeSettings>();
        
        if (settings?.DaysOfWeek is null || settings.DaysOfWeek.Length == 0)
        {
            return Task.FromResult(true);
        }

        var now = DateTime.UtcNow;
        var dayOfWeek = now.DayOfWeek.ToString();
        
        return Task.FromResult(settings.DaysOfWeek.Contains(dayOfWeek));
    }
}

public class RecurringTimeSettings
{
    public string[] DaysOfWeek { get; set; } = Array.Empty<string>();
}
模式 7:中间件和管道集成

将功能标志集成到中间件中,实现请求级别的控制。

// Feature flag middleware
public class FeatureFlagMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<FeatureFlagMiddleware> _logger;

    public FeatureFlagMiddleware(RequestDelegate next, ILogger<FeatureFlagMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task InvokeAsync(
        HttpContext context, 
        IFeatureManager featureManager)
    {
        // Add feature flags to HttpContext.Items for views
        var flags = new Dictionary<string, bool>
        {
            [FeatureFlags.NewDashboard] = await featureManager.IsEnabledAsync(FeatureFlags.NewDashboard),
            [FeatureFlags.DarkMode] = await featureManager.IsEnabledAsync(FeatureFlags.DarkMode)
        };
        
        context.Items["FeatureFlags"] = flags;

        // Check for API rate limiting feature
        if (await featureManager.IsEnabledAsync(FeatureFlags.ApiRateLimiting))
        {
            _logger.LogDebug("API rate limiting is enabled");
        }

        await _next(context);
    }
}

// Extension method
public static class FeatureFlagMiddlewareExtensions
{
    public static IApplicationBuilder UseFeatureFlags(this IApplicationBuilder app)
    {
        return app.UseMiddleware<FeatureFlagMiddleware>();
    }
}

// Usage in Program.cs
app.UseFeatureFlags();

// View helper
public static class FeatureFlagHelpers
{
    public static bool IsFeatureEnabled(this IHtmlHelper helper, string featureName)
    {
        var flags = helper.ViewContext.HttpContext.Items["FeatureFlags"] 
            as Dictionary<string, bool>;
        
        return flags?.TryGetValue(featureName, out var enabled) == true && enabled;
    }
}

// View usage
@if (Html.IsFeatureEnabled(FeatureFlags.DarkMode))
{
    <script>/* Dark mode logic */</script>
}

反模式

// ❌ BAD: Hard-coded feature checks scattered throughout code
if (Environment.IsDevelopment())
{
    ShowNewFeature();
}

// ✅ GOOD: Use feature manager
if (await _featureManager.IsEnabledAsync(FeatureFlags.NewFeature))
{
    ShowNewFeature();
}

// ❌ BAD: Checking features in tight loops
for (var item in items)
{
    if (await _featureManager.IsEnabledAsync(FeatureFlags.BatchProcessing))
    {
        ProcessBatch(item);
    }
}

// ✅ GOOD: Check once and cache result
var useBatchProcessing = await _featureManager.IsEnabledAsync(FeatureFlags.BatchProcessing);
foreach (var item in items)
{
    if (useBatchProcessing)
    {
        ProcessBatch(item);
    }
}

// ❌ BAD: Not handling missing configuration
public async Task<bool> IsNewFeatureEnabled()
{
    return await _featureManager.IsEnabledAsync("NewFeature"); // May throw!
}

// ✅ GOOD: Use constants and handle gracefully
public async Task<bool> IsNewFeatureEnabled()
{
    try
    {
        return await _featureManager.IsEnabledAsync(FeatureFlags.NewFeature);
    }
    catch (FeatureManagementException ex)
    {
        _logger.LogWarning(ex, "Feature flag check failed");
        return false; // Safe fallback
    }
}

// ❌ BAD: Tight coupling to feature manager in domain logic
public class OrderService
{
    private readonly IFeatureManager _featureManager; // Shouldn't be here!
    
    public async Task ProcessOrder(Order order)
    {
        if (await _featureManager.IsEnabledAsync("NewPricing"))
        {
            ApplyNewPricing(order);
        }
    }
}

// ✅ GOOD: Pass feature-driven behavior as configuration/strategy
public class OrderService
{
    private readonly IPricingStrategy _pricingStrategy;
    
    public OrderService(IPricingStrategy pricingStrategy)
    {
        _pricingStrategy = pricingStrategy;
    }
    
    public Task ProcessOrder(Order order)
    {
        _pricingStrategy.ApplyPricing(order);
        // ...
    }
}

// ❌ BAD: Not cleaning up old feature flags
// appsettings.json has 50+ old flags never cleaned up

// ✅ GOOD: Regular cleanup process
// 1. Document feature flag lifecycle
// 2. Remove flags after feature is fully rolled out
// 3. Use feature flag dashboard for tracking

// ❌ BAD: Inconsistent naming conventions
{
  "new_feature": true,
  "LegacyFeature": false,
  "AnotherFeature_V2": true
}

// ✅ GOOD: Consistent naming (PascalCase recommended)
{
  "NewFeature": true,
  "LegacyFeature": false,
  "AnotherFeatureV2": true
}

// ❌ BAD: Enabling features without monitoring
await _featureManager.IsEnabledAsync("ExpensiveFeature");
// No metrics on usage!

// ✅ GOOD: Instrument feature flag usage
public async Task<bool> IsEnabledWithMetrics(string featureName)
{
    var enabled = await _featureManager.IsEnabledAsync(featureName);
    
    _metrics.RecordFeatureFlagCheck(featureName, enabled);
    
    return enabled;
}

参考资料

评论

支持 Markdown