NET Core 程序特性開關之Microsoft.FeatureManagement.AspNetCore 擴展包


給你的 ASP.NET Core 程序插上 Feature Flag 的翅膀

 

前言#

我們知道,目前大多數應用程序在正式發布到生產環境之前都會經歷多個不同的測試環境,通過讓應用程序在多個不同的環境中運行來及時發現並解決問題,避免在線上發生不必要的損失。這是對於整個軟件的發布流程來講。但是如果想讓我們的應用程序在線上環境中通過滿足一些動態條件(比如電商平台在某一時間段的促銷活動)從而能開啟一些臨時功能的話又該怎么辦呢?如果你試圖通過重新打包發布的方式來解決這個問題,可能有些過於大動干戈了。本文,筆者將介紹通過 Feature Flag 的方式來解決這個問題。

正文#

Feature Flag 中文可譯為 功能開關。通過使用這種方式,可以對我們的功能進行條件化配置,當程序在線上環境運行時,如果當前環境符合我們某一特性功能開啟/關閉的條件時,應用程序會自動開啟/關閉該功能。整個過程不需要人工參與,全部都是由系統本身來完成相應功能的開啟和關閉。

那在 .NET Core 中,我們該如何實現該功能呢?

微軟為我們很貼心地提供了兩個開發包:Microsoft.FeatureManagement 和 Microsoft.FeatureManagement.AspNetCore,該實現是基於 .NET Core 的配置系統 ,所以任何 .NET Core 程序都可以輕易集成該功能。

目前還處於預覽版階段,需要在 NuGet 上勾選 use prerelease

因此,我們只需將對應包安裝到我們的應用程序中即可。

接下來,我們就一起看一下如何在 ASP.NET Core 中集成該功能。

使用入門#

創建一個 ASP.NET Core Web Application 后,安裝如下包:

Install-Package Microsoft.FeatureManagement.AspNetCore -Version 2.0.0-preview-010610001-1263

接着在 Startup 中的 ConfigureServices 進行相應配置,示例如下:

Copy
public void ConfigureServices(IServiceCollection services) { services.AddFeatureManagement(); services.AddControllersWithViews(); }

至此,我們的程序已經支持 Feature Flag 功能了,使用方式就簡單了,這里展示一個相對簡單的方式。

首先,在 appsettings.json 進行配置,如下所示:

Copy
  "FeatureManagement": { "NewFeatureFlag": true, }

然后,在 Index.cshtml 通過使用 feature 標簽來進行相應配置,示例如下所示:

Copy
@using Microsoft.FeatureManagement
@inject IFeatureManager FeatureManager
@addTagHelper *,Microsoft.FeatureManagement.AspNetCore
@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center"> <h1 class="display-4">Welcome</h1> <feature name="NewFeatureFlag" requirement="All"> <a asp-action="NewFeature">Go to the new feature.</a> </feature> </div>

此時,我們運行起程序后就可以看到 feature 標簽內的內容就可以渲染出來,如果我們在配置中將 NewFeatureFlag 值設置為 False 后,feature 標簽內的內容就會消失,你可以通過查看網頁源碼的方式來查看具體細節。

接下來筆者介紹一下微軟為我們內置的兩個功能開關:

PercentageFilter#

PercentageFilter 是支持百分比的隨機開關,通過使用這種方式,可以讓一個功能在每次請求中以一個百分比概率的形式來開啟/關閉。

  • 注入功能開關

Startup.cs

Copy
public void ConfigureServices(IServiceCollection services) { services.AddFeatureManagement() .AddFeatureFilter<PercentageFilter>(); services.AddControllersWithViews(); }
  • 配置功能開關

appsettings.json

Copy
  "FeatureManagement": { "RandomFlag": { "EnabledFor": [ { "Name": "Percentage", "Parameters": { "Value": 50 } } ] } }

這里配置的是在每次請求時以 50% 的概率來開啟該功能,其對應的配置類為:PercentageFilterSettings

  • 使用功能開關

Index.cshtml

Copy
@using Microsoft.FeatureManagement
@inject IFeatureManager FeatureManager
@addTagHelper *,Microsoft.FeatureManagement.AspNetCore
@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center"> <h1 class="display-4">Welcome</h1> <feature name="RandomFlag"> <h2>I am a Random Flag!</h2> </feature> <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p> </div>

這時,當我們運行起程序后就會看到如下圖所示的效果:

TimeWindowFilter#

TimeWindowFilter 是時間段的隨機開關,通過使用這種方式,可以讓一個功能在指定的時間段內來開啟/關閉。

  • 注入功能開關

Startup.cs

Copy
public void ConfigureServices(IServiceCollection services) { services.AddFeatureManagement() .AddFeatureFilter<TimeWindowFilter>(); services.AddControllersWithViews(); }
  • 配置功能開關

appsettings.json

Copy
  "FeatureManagement": { "RandomFlag": { "EnabledFor": [ { "Name": "Percentage", "Parameters": { "Start": "2019/12/27 5:04:00 +00:00", "End": "2019/12/27 5:04:05 +00:00" } } ] } }

這里需要注意的是,配置里面的 Start 和 End 是 DateTimeOffset 類型,並且需要配置為 UTC 的時間,所以在實際使用過程中需要考慮時區問題(你可以通過調用 DateTimeOffset.UtcNow 的方式來獲取相應時間的格式)。其對應的配置類為:TimeWindowFilterSettings

  • 使用功能開關

Index.cshtml

Copy
@using Microsoft.FeatureManagement
@inject IFeatureManager FeatureManager
@addTagHelper *,Microsoft.FeatureManagement.AspNetCore
@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center"> <h1 class="display-4">Welcome</h1> <feature name="TimedFlag"> <h2>I am a Timed Flag!</h2> </feature> <p>@DateTimeOffset.UtcNow.ToString()</p> <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p> </div>

這時,當我們運行起程序后就會看到如下圖所示的效果:

自定義功能開關#

最后要介紹的是如果創建和使用自定義的功能開關,筆者這里做一個這樣的示例,當網站被 Microsoft Edge 瀏覽器訪問時,顯示功能,其余瀏覽器則隱藏功能。

這里,筆者創建一個配置的映射類 BrowserFilterSettings 和執行過濾的操作類 BrowserFeatureFilter,示例代碼如下所示:

Copy
public class BrowserFilterSettings { public string[] AllowedBrowsers { get; set; } } [FilterAlias("BrowserFilter")] public class BrowserFeatureFilter : IFeatureFilter { private readonly IHttpContextAccessor _httpContextAccessor; public BrowserFeatureFilter(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; } public Task<bool> EvaluateAsync(FeatureFilterEvaluationContext context) { var userAgent = _httpContextAccessor.HttpContext.Request.Headers["User-Agent"].ToString(); var settings = context.Parameters.Get<BrowserFilterSettings>(); return Task.FromResult(settings.AllowedBrowsers.Any(userAgent.Contains)); } }

接着,進行功能開關的注入,示例代碼如下所示:

Copy
public void ConfigureServices(IServiceCollection services) { services.AddHttpContextAccessor(); services.AddFeatureManagement() .AddFeatureFilter<BrowserFeatureFilter>(); services.AddControllersWithViews(); }

然后,進行功能開關的配置,示例配置如下所示:

Copy
  "FeatureManagement": { "BrowserFlag": { "EnabledFor": [ { "Name": "BrowserFilter", "Parameters": { "AllowedBrowsers": [ "Edge" ] } } ] } }

接着,使用方式如下所示:

Copy
@using Microsoft.FeatureManagement
@inject IFeatureManager FeatureManager
@addTagHelper *,Microsoft.FeatureManagement.AspNetCore
@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center"> <h1 class="display-4">Welcome</h1> <feature name="BrowserFlag"> <h2>I am a Browser Flag only on Edge!</h2> </feature> <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p> </div>

這時,當我們分別用 Microsoft Edge 和 Google Chrome 訪問站點時就會看到如下圖所示的效果:

總結#

借助於 Microsoft.FeatureManagement.AspNetCore 擴展包,我們可以很容易實現 Feature Flag 效果。又由於這種實現是基於 IConfiguration 的,所以很具有通用性。這里列出官方給出的優點:

  • A common convention for feature management
  • Low barrier-to-entry
    • Built on IConfiguration
    • Supports JSON file feature flag setup
  • Feature Flag lifetime management
    • Configuration values can change in real-time, feature flags can be consistent across the entire request
  • Simple to Complex Scenarios Covered
    • Toggle on/off features through declarative configuration file
    • Dynamically evaluate state of feature based on call to server
      API extensions for ASP.NET Core and MVC framework
    • Routing
    • Filters
    • Action Attributes

非常感謝你能閱讀這篇文章,希望它能對你有所幫助。

相關參考#


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM