ASP NET Core 2 0 全局配置项

本文介绍了在ASP.NET Core 2.0中如何读取全局配置项,包括创建appsettings.json和appsettings.Development.json文件,定义POCO类,通过依赖注入在Startup.cs中使用配置项。文中还探讨了配置文件的加载顺序以及如何通过IConfiguration读取不同配置节。同时,展示了如何手动设置配置项的值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

               

问题

如何在 ASP.NET Core 2.0 应用程序中读取全局配置项?

答案

首先新建一个空项目,并添加两个配置文件:

1. appsettings.json

{  "Section1": {    "SettingA": "ValueA",    "SettingB": "ValueB"  },  "Section2": {    "SettingC": "ValueC"  }}


2. appsettings.Development.json


{  "Section1": {    "SettingA": "Dev_ValueA"  },  "Section2": {    "SettingC": "Dev_ValueC"  }}

Visual Studio会自动识别两者的关系,并在解决方案层次结构中展示如下:

640?wx_fmt=png&wxfrom=5&wx_lazy=1

然后创建相应的POCO类,分别对应于几个配置节点:


public class AppSettings{   
 public AppSettingsSection1 Section1 { get; set; }    public AppSettingsSection2 Section2 { get; set; }}

public class AppSettingsSection1{  
 public string SettingA { get; set; }  

 public string SettingB { get; set; }}

public class AppSettingsSection2{  
  public string SettingC { get; set; }}


在Startup.cs文件中,创建接收 IConfiguration 的构造函数:

public static IConfiguration Configuration { get;
private set;}

public Startup(IConfiguration config){    Configuration = config;}

然后在 ConfigureServices() 方法中添加Options服务,并设置依赖项:

public void ConfigureServices(IServiceCollection services){    services.AddOptions();    services.Configure<AppSettings>(Configuration);}

最后,将配置项作为IOptions接口注入中间件的构造函数,其中泛型类型T就是我们刚才定义的POCO类:


public class HelloWorldMiddleware{   

 private readonly RequestDelegate _next;  
 private readonly AppSettings _settings;

  public HelloWorldMiddleware(RequestDelegate next, IOptions<AppSettings> options)    {        _next = next;        _settings = options.Value;    }  

 public async Task Invoke(HttpContext context)    {      
    var jsonSettings = JsonConvert.SerializeObject(_settings, Formatting.Indented);    
   await context.Response.WriteAsync(jsonSettings);    }}

public static class UseHelloWorldInClassExtensions{  
   public static IApplicationBuilder UseHelloWorld(this IApplicationBuilder app)    {      
  return app.UseMiddleware<HelloWorldMiddleware>();    }}

在Startup.cs的 Configure() 方法中,将此中间件注入到请求管道中:

public void Configure(IApplicationBuilder app, IHostingEnvironment env){    app.UseHelloWorld();}

运行,此时页面显示:

0?wx_fmt=png

讨论

 ASP.NET Core 拥有一个简单的机制来从各种数据源(比如JSON文件,环境变量,甚至是自定义数据源)中读取应用程序设置。然后通过依赖注入,方便的使用这些配置项。

尽管这一切看起来很魔幻(我们的设置究竟是如何加载的!),ASP.NET Core 2.0隐藏了从数据源中读取配置项的细节,这些内容本应该存在于Program.cs文件中WebHost的CreateDefaultBuilder()方法中。IConfiguration随后被添加到服务容器中,并在应用程序的其他部分保持可用,我们使用Startup中的此接口来添加配置项。为了观察这个过程,请将Program.cs文件中的BuildWebHost()方法替换为如下内容,得到的结果是一样的:

public static IWebHost BuildWebHost(string[] args) =>    WebHost.CreateDefaultBuilder(args)        .UseStartup<Startup>()        .ConfigureAppConfiguration((context, builder) =>        {            var env = context.HostingEnvironment;            builder.AddJsonFile("appsettings.json",                         optional: true, reloadOnChange: true)                   .AddJsonFile($"appsettings.{env.EnvironmentName}.json",                         optional: true, reloadOnChange: true);            

if (env.IsDevelopment())            {              
 var appAssembly = Assembly.Load(                    new AssemblyName(env.ApplicationName));      
          if (appAssembly != null)                {                    builder.AddUserSecrets(appAssembly, optional: true);                }            }            builder.AddEnvironmentVariables();            if (args != null)            {                builder.AddCommandLine(args);            }        })        .Build();

在上面的解决方案中,我们提供了两个JSON文件数据源。需要记着的一点是,这些文件按照顺序被依次读取,后面的数据源会覆盖前面的数据源。你也可以在上面的运行结果中注意到,SettingB配置项来自于第一个配置文件,而其他两个配置项都来自于第二个配置文件。

注意:Startup.cs中的IConfiguration实例拥有public static修饰符,因此可以在整个应用程序期间使用此实例:

var valueA = Config["Section1:SettingA"];

然而,更好的办法是将配置项读入一个类型化的POCO类,并将其作为依赖项注入中间件或者控制器。上面的示例正好展示了这个模式。

你也可以为不同的配置节定义不同的POCO类,并使用IConfiguration的GetSection()方法来读取。

 

====start by sanshi=========================

下面我们简单扩展之前的示例,来读取不同的配置节:

public void ConfigureServices(IServiceCollection services){    services.AddOptions();    services.Configure<AppSettings>(Configuration);    services.Configure<AppSettingsSection1>(Configuration.GetSection("Section1"));}

更新中间件代码,此时向中间件的构造函数注入两个依赖项:


public class HelloWorldMiddleware{   
 private readonly RequestDelegate _next;  
 private readonly AppSettings _settings;    

private readonly AppSettingsSection1 _settingsSection1;  

 public HelloWorldMiddleware(RequestDelegate next, IOptions<AppSettings> options, IOptions<AppSettingsSection1> optionsSection1)    {        _next = next;        _settings = options.Value;        _settingsSection1 = optionsSection1.Value;    }    

public async Task Invoke(HttpContext context)    {      
 var jsonSettings = JsonConvert.SerializeObject(_settings, Formatting.Indented);      
 var jsonSettingsSection1 = JsonConvert.SerializeObject(_settingsSection1, Formatting.Indented);    
   await context.Response.WriteAsync("AppSettings:\n" + jsonSettings + "\n\nAppSettings - Section1:\n" + jsonSettingsSection1);    }}


运行,此时页面显示:

0?wx_fmt=png

====end by sanshi=========================

 

当然,我们也可以手工设置配置项的值,通过使用IServiceCollection.Configure的重载方法并接收强类型的lambda表达式:

====start by sanshi=========================

 修改ConfigurationServices()方法,手工设置配置项:

public void ConfigureServices(IServiceCollection services){    services.AddOptions();        services.Configure<AppSettings>(options =>    {        options.Section1 = new AppSettingsSection1();        options.Section1.SettingA = "SettingA Value";        options.Section1.SettingB = "SettingB Value";    });}


运行,此时页面效果:

0?wx_fmt=png

====end by sanshi========================= 

原文:https://tahirnaushad.com/2017/08/15/asp-net-core-configuration/


原文地址:http://www.cnblogs.com/zhaopei/p/SSO.html


.NET社区新闻,深度好文,微信中搜索dotNET跨平台或扫描二维码关注

640?wx_fmt=jpeg

           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.youkuaiyun.com/jiangjunshow

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值