每个.NET团队都会撞上同一堵墙:staging环境里的功能已经ready,但推到生产环境意味着给所有用户同时开闸。一旦出问题——假设错误、边界情况、性能回退——唯一的救命稻草就是回滚和重新部署。
特性开关(Feature Flags)把部署和发布拆开。代码裹着开关上线,然后从控制台决定谁看得见,全程不用碰流水线。先给1%用户,盯紧指标,再扩到100%。任何阶段报错飙升,几秒钟就能关开关。
![]()
本文基于.NET 8,演示如何在ASP.NET Core、Minimal API和Blazor里落地。SDK以Rollgate为例,但思路适用于任何特性开关服务。
第一步:装包与初始化
从NuGet安装SDK:
dotnet add package Rollgate.SDK
应用启动时初始化客户端:
using Rollgate.SDK;
var client = new RollgateClient(new RollgateConfig
ApiKey = Environment.GetEnvironmentVariable("ROLLGATE_API_KEY") ?? "",
await client.InitializeAsync();
if (client.IsEnabled("new-checkout", false))
Console.WriteLine("New checkout enabled");
client.Dispose();
InitializeAsync()完成后,每次IsEnabled调用都走内存字典——开销是个位数微秒。
第二步:依赖注入注册
ASP.NET Core里把客户端注册为单例,再加一层IFeatureFlags抽象,方便控制器测试:
// Program.cs
builder.Services.AddSingleton(sp =>
var client = new RollgateClient(new RollgateConfig
ApiKey = builder.Configuration["Rollgate:ApiKey"] ?? "",
RefreshInterval = TimeSpan.FromSeconds(30),
// 教程简化。生产环境建议用IHostedService
client.InitializeAsync().GetAwaiter().GetResult();
return client;
builder.Services.AddSingleton();
public interface IFeatureFlags
bool IsEnabled(string flagKey, bool defaultValue = false);
public sealed class RollgateFeatureFlags : IFeatureFlags
private readonly RollgateClient _client;
public RollgateFeatureFlags(RollgateClient client) => _client = client;
public bool IsEnabled(string key, bool def = false) => _client.IsEnabled(key, def);
第三步:控制器里使用
注入IFeatureFlags,不要直接依赖SDK类型:
[ApiController]
[Route("api/[controller]")]
特别声明:以上内容(如有图片或视频亦包括在内)为自媒体平台“网易号”用户上传并发布,本平台仅提供信息存储服务。
Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.