慣性聚合 高效追讀感興趣之博客、新聞、科技資訊
閱原文 以慣性聚合開啟

推薦訂閱源

Google DeepMind News
Google DeepMind News
人人都是产品经理
人人都是产品经理
M
MIT News - Artificial intelligence
博客园 - 叶小钗
MyScale Blog
MyScale Blog
V
Visual Studio Blog
月光博客
月光博客
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
量子位
I
InfoQ
有赞技术团队
有赞技术团队
阮一峰的网络日志
阮一峰的网络日志
Jina AI
Jina AI
V
V2EX
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Blog — PlanetScale
Blog — PlanetScale
Last Week in AI
Last Week in AI
雷峰网
雷峰网
Stack Overflow Blog
Stack Overflow Blog
博客园 - Franky

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python)
.NET 8 中之特性标志:ASP.NET Core、极简 API、Blazor
Domenico Gio · 2026-05-25 · via DEV Community

此帖初载于rollgate.io/blog/功能标志-ASP.NET Core.

凡.NET之众,终遇同障:既成之功能,或立於试场,然推之於实境,则须一转其钥,使众皆受之。倘有倾覆——或因谬识,或缘奇境,或致迟滞——则唯可回撤重布,以图补救。

特性标志以分离部署与发布而解此困。将代码隐于旗之后,自仪表盘控其见者,不触管廊。初试百分之一之用,察其度数,渐扩至百。若误骤增于任阶,秒息可禁其旗。

快启:.NET 8 之特性旗

自 NuGet 安 Rollgate 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<RollgateClient>(sp =>
{
    var client = new RollgateClient(new RollgateConfig
    {
        ApiKey = builder.Configuration["Rollgate:ApiKey"] ?? "",
        RefreshInterval = TimeSpan.FromSeconds(30),
    });
    // Tutorial simplicity. In production, prefer IHostedService.
    client.InitializeAsync().GetAwaiter().GetResult();
    return client;
});

builder.Services.AddSingleton<IFeatureFlags, RollgateFeatureFlags>();

入全屏模式 出全屏模式

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);
}

入全屏模式 出全屏模式

ASP.NET Core控制器中特征标志

当注IFeatureFlags,勿直注SDK之型:

[ApiController]
[Route("api/[controller]")]
public class CheckoutController : ControllerBase
{
    private readonly IFeatureFlags _flags;

    public CheckoutController(IFeatureFlags flags) => _flags = flags;

    [HttpPost]
    public async Task<IActionResult> CreateOrder([FromBody] OrderRequest request)
    {
        return _flags.IsEnabled("checkout-v2", false)
            ? Ok(await ProcessV2Async(request))
            : Ok(await ProcessV1Async(request));
    }
}

入全屏模式 出全屏模式

识用户——每会一次,非每请一次

RollgateClient.IdentifyAsync发HTTP请,触旗标更。勿于每请而唤之——是增端点一网络往返,且殒内存评模。

其位宜者,为行之滤,每用者一,则顿止:

public class FeatureFlagIdentityFilter : IAsyncActionFilter
{
    private readonly RollgateClient _client;
    private static readonly HashSet<string> _identified = new();
    private static readonly SemaphoreSlim _gate = new(1, 1);

    public FeatureFlagIdentityFilter(RollgateClient client) => _client = client;

    public async Task OnActionExecutionAsync(ActionExecutingContext ctx, ActionExecutionDelegate next)
    {
        var userId = ctx.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (!string.IsNullOrEmpty(userId) && !_identified.Contains(userId))
        {
            await _gate.WaitAsync();
            try
            {
                if (!_identified.Contains(userId))
                {
                    await _client.IdentifyAsync(new UserContext { Id = userId });
                    _identified.Add(userId);
                }
            }
            finally { _gate.Release(); }
        }
        await next();
    }
}

入全屏模式 出全屏模式

洁于产:登录时一唤IdentifyAsync,未出前不再唤。

最简API中特征之旗

app.MapPost("/api/search", async (SearchRequest req, IFeatureFlags flags) =>
{
    return flags.IsEnabled("semantic-search", false)
        ? Results.Ok(await RunSemanticSearchAsync(req.Query))
        : Results.Ok(await RunKeywordSearchAsync(req.Query));
});

入全屏模式 出全屏模式

通途一径,以端点之滤,解IFeatureFlags于请务:

public static class FeatureFlagEndpointExtensions
{
    public static TBuilder RequireFeature<TBuilder>(this TBuilder builder, string flagKey)
        where TBuilder : IEndpointConventionBuilder
    {
        return builder.AddEndpointFilter(async (context, next) =>
        {
            var flags = context.HttpContext.RequestServices.GetRequiredService<IFeatureFlags>();
            if (!flags.IsEnabled(flagKey, false)) return Results.NotFound();
            return await next(context);
        });
    }
}

app.MapGet("/api/v2/analytics", GetAnalyticsV2Handler)
   .RequireFeature("analytics-v2")
   .RequireAuthorization();

全屏模式入 全屏模式出

鲍尔佐服务器之特徵旗

@page "/checkout"
@inject IFeatureFlags Flags
@inject AuthenticationStateProvider AuthStateProvider

@if (_showNewCheckout) { <NewCheckoutFlow /> } else { <LegacyCheckoutFlow /> }

@code {
    private bool _showNewCheckout;

    protected override void OnInitialized()
    {
        // Runs once per circuit, not per render.
        _showNewCheckout = Flags.IsEnabled("checkout-v2", false);
    }
}

全屏模式入 全屏模式出

鲍尔佐网页组件,于Program.cs前,自服务器取旗RunAsync()

var host = builder.Build();
await host.Services.GetRequiredService<FlagService>().LoadAsync();
await host.RunAsync();

入全屏模式

测试C语言中的特性标志

:自控制器依IFeatureFlags,无需模拟框架:

public class FakeFeatureFlags : IFeatureFlags
{
    private readonly Dictionary<string, bool> _flags;
    public FakeFeatureFlags(Dictionary<string, bool>? f = null) => _flags = f ?? new();
    public bool IsEnabled(string key, bool def = false)
        => _flags.TryGetValue(key, out var v) ? v : def;
}

public class CheckoutControllerTests
{
    [Fact]
    public async Task Returns_V2_When_Flag_Enabled()
    {
        var flags = new FakeFeatureFlags(new() { ["checkout-v2"] = true });
        var controller = new CheckoutController(flags);
        var result = await controller.CreateOrder(new OrderRequest { Amount = 99 });
        // assert v2 path
    }
}

__JHSNS_SEG_1a03b836_48__:__JHSNS_SEG_1a03b836_49__出全屏模式__JHSNS_SEG_1a03b836_50__:__JHSNS_SEG_1a03b836_51__ 渐进式发布与用户定向

识人之际(每会一次),当传用户之属。

await _client.IdentifyAsync(new UserContext
{
    Id = userId,
    Email = userEmail,
    Attributes = new Dictionary<string, object?>
    {
        ["plan"] = user.SubscriptionPlan,
        ["country"] = user.Country,
    }
});

入全景模式 出全景模式

于仪表盘设百分比铺展与属之靶向——SDK于本地评诸规,无每评之API呼。

诸问

二零二六,.NET之特征旗何术?

  • 简易之切换,无运行时之变——Microsoft.FeatureManagement
  • CNCF中立厂商SDK→OpenFeature .NET
  • 仪表盘+目标定位+渐进式发布→管理服务(Rollgate, LaunchDarkly等)

.NET 背景服务可与之相合乎?
然。注册RollgateClient为独体,注入之BackgroundService,用IsEnabledExecuteAsync.

何若InitializeAsync启动之际,其功不就。
若无缓存,则抛出异常。或捕获之,依默认值继续;或任其显现(速败通常更安全)。


览全文——含断路器配置、杀软开关之SSE流式传输、及Blazor WebAssembly模式——于rollgate.io/blog/功能标志-ASP.NET Core

创 Rollgate 免费账户于https://app.rollgate.io/register — 无需信用卡。