做网站要多钱,竞价托管一般多少钱,高端网络公司网站源码,上海网站建设雍熙.NET Core 中的 功能管理 (Feature Management) 包可用于实现 功能开关#xff0c;什么意思呢#xff1f;就是可以通过 功能开关 特性动态的改变应用程序的行为而不需要改变任何的业务逻辑代码#xff0c;听起来是不是挺有意思#xff0c;本篇我们就来讨论如何使用这个包。… .NET Core 中的 功能管理 (Feature Management) 包可用于实现 功能开关什么意思呢就是可以通过 功能开关 特性动态的改变应用程序的行为而不需要改变任何的业务逻辑代码听起来是不是挺有意思本篇我们就来讨论如何使用这个包。安装 Feature Management 包 要想使用 功能管理需要通过 NuGet 安装 Microsoft.FeatureManagement.AspNetCore可通过 Visual Studio 2019 下的 NuGet Package Manager 可视化管理界面 或者 通过 .NET CLI 命令行工具输入如下命令。
dotnet add package Microsoft.FeatureManagement.AspNetCore在 ASP.NET Core 中添加 为了能够在项目中用上 功能管理需要在 Startup.ConfigureServices 方法下进行 service 注入如下代码所示public class Startup{// This method gets called by the runtime. Use this method to add services to the container.public void ConfigureServices(IServiceCollection services){services.AddControllersWithViews();services.AddFeatureManagement();}}有一点要注意功能管理 中的 功能开关 读取的值来自于 .NET Core 中的配置文件如果你想让 功能开关 的值来源于 Configuration 文件的不同节点必须在 service 注册时单独指定一下如下代码所示public void ConfigureServices(IServiceCollection services){services.AddFeatureManagement(options {options.UseConfiguration(Configuration.GetSection(IDGFeatureFlags));});}在 controller 中使用 功能管理 为了能够在 Controller 中用上 功能管理(feature management)需要通过依赖注入的方式将其注入到 Controller 中如下代码所示:
public class HomeController : Controller
{private readonly ILoggerHomeController _logger;private readonly IFeatureManager _featureManager;public HomeController(ILoggerHomeController logger, IFeatureManagerSnapshot featureManager){_logger logger;_featureManager featureManager;}
}接下来在 appsettings.json 配置文件中定义一个名为 FeatureManagement 节点文件内容参考如下
{Logging: {LogLevel: {Default: Information,Microsoft: Warning,Microsoft.Hosting.Lifetime: Information}},FeatureManagement: {DbLogger: true},AllowedHosts: *
}使用 FeatureGate特性 管控 功能开关 可以使用 FeatureGate 特性来 管控 Action 方法是否可以被执行什么意思呢先看如下代码。public class HomeController : Controller{private readonly ILoggerHomeController _logger;private readonly IFeatureManager _featureManager;public HomeController(ILoggerHomeController logger, IFeatureManagerSnapshot featureManager){_logger logger;_featureManager featureManager;}[FeatureGate(DbLogger)]public IActionResult Index(){return View();}}可以看到 Index 方法标注了 [FeatureGate(DbLogger)] 特性这里面的 DbLogger 就是 appsettings.json 中的 DbLogger 节点的值当值为 True 时这个 Index 方法是可以被 HttpGet 所请求的如下图当值为 False 时这个 Index 方法将会抛出 404 错误是不是很有意思哈如下图所示
{Logging: {LogLevel: {Default: Information,Microsoft: Warning,Microsoft.Hosting.Lifetime: Information}},FeatureManagement: {DbLogger: false},AllowedHosts: *
}用法就是这么一个用法可以看到 .NET Core 对 功能管理 提供了开箱即用的支持 这确实是一个非常实用的特性更多关于该 知识点 的介绍可参考官网https://docs.microsoft.com/en-us/azure/azure-app-configuration/use-feature-flags-dotnet-core译文链接https://www.infoworld.com/article/3481516/how-to-use-feature-flags-in-aspnet-core.html