ASP.NET Core 2.0 全局配置项
問題
如何在 ASP.NET Core 2.0 應(yīng)用程序中讀取全局配置項(xiàng)?
答案
首先新建一個(gè)空項(xiàng)目,并添加兩個(gè)配置文件:
1. appsettings.json
{ ?"Section1": { ? ?"SettingA": "ValueA", ? ?"SettingB": "ValueB"}, ?"Section2": { ? ?"SettingC": "ValueC"} }
2.?appsettings.Development.json
Visual?Studio會(huì)自動(dòng)識(shí)別兩者的關(guān)系,并在解決方案層次結(jié)構(gòu)中展示如下:
然后創(chuàng)建相應(yīng)的POCO類,分別對(duì)應(yīng)于幾個(gè)配置節(jié)點(diǎn):
?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文件中,創(chuàng)建接收 IConfiguration 的構(gòu)造函數(shù):
public static IConfiguration Configuration { get;private set;}
public Startup(IConfiguration config) {Configuration = config; }
然后在 ConfigureServices()?方法中添加Options服務(wù),并設(shè)置依賴項(xiàng):
public void ConfigureServices(IServiceCollection services) {services.AddOptions();services.Configure<AppSettings>(Configuration); }最后,將配置項(xiàng)作為IOptions接口注入中間件的構(gòu)造函數(shù),其中泛型類型T就是我們剛才定義的POCO類:
?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(); }運(yùn)行,此時(shí)頁面顯示:
討論
?ASP.NET Core?擁有一個(gè)簡單的機(jī)制來從各種數(shù)據(jù)源(比如JSON文件,環(huán)境變量,甚至是自定義數(shù)據(jù)源)中讀取應(yīng)用程序設(shè)置。然后通過依賴注入,方便的使用這些配置項(xiàng)。
盡管這一切看起來很魔幻(我們的設(shè)置究竟是如何加載的!),ASP.NET Core 2.0隱藏了從數(shù)據(jù)源中讀取配置項(xiàng)的細(xì)節(jié),這些內(nèi)容本應(yīng)該存在于Program.cs文件中WebHost的CreateDefaultBuilder()方法中。IConfiguration隨后被添加到服務(wù)容器中,并在應(yīng)用程序的其他部分保持可用,我們使用Startup中的此接口來添加配置項(xiàng)。為了觀察這個(gè)過程,請將Program.cs文件中的BuildWebHost()方法替換為如下內(nèi)容,得到的結(jié)果是一樣的:
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();
在上面的解決方案中,我們提供了兩個(gè)JSON文件數(shù)據(jù)源。需要記著的一點(diǎn)是,這些文件按照順序被依次讀取,后面的數(shù)據(jù)源會(huì)覆蓋前面的數(shù)據(jù)源。你也可以在上面的運(yùn)行結(jié)果中注意到,SettingB配置項(xiàng)來自于第一個(gè)配置文件,而其他兩個(gè)配置項(xiàng)都來自于第二個(gè)配置文件。
注意:Startup.cs中的IConfiguration實(shí)例擁有public?static修飾符,因此可以在整個(gè)應(yīng)用程序期間使用此實(shí)例:
var valueA = Config["Section1:SettingA"];然而,更好的辦法是將配置項(xiàng)讀入一個(gè)類型化的POCO類,并將其作為依賴項(xiàng)注入中間件或者控制器。上面的示例正好展示了這個(gè)模式。
你也可以為不同的配置節(jié)定義不同的POCO類,并使用IConfiguration的GetSection()方法來讀取。
?
====start by sanshi=========================
下面我們簡單擴(kuò)展之前的示例,來讀取不同的配置節(jié):
public void ConfigureServices(IServiceCollection services) {services.AddOptions();services.Configure<AppSettings>(Configuration);services.Configure<AppSettingsSection1>(Configuration.GetSection("Section1")); }更新中間件代碼,此時(shí)向中間件的構(gòu)造函數(shù)注入兩個(gè)依賴項(xiàng):
?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);} }
運(yùn)行,此時(shí)頁面顯示:
====end by sanshi=========================
?
當(dāng)然,我們也可以手工設(shè)置配置項(xiàng)的值,通過使用IServiceCollection.Configure的重載方法并接收強(qiáng)類型的lambda表達(dá)式:
====start by sanshi=========================
?修改ConfigurationServices()方法,手工設(shè)置配置項(xiàng):
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";}); }
運(yùn)行,此時(shí)頁面效果:
====end by sanshi=========================?
原文:https://tahirnaushad.com/2017/08/15/asp-net-core-configuration/
原文地址:http://www.cnblogs.com/zhaopei/p/SSO.html
.NET社區(qū)新聞,深度好文,微信中搜索dotNET跨平臺(tái)或掃描二維碼關(guān)注
總結(jié)
以上是生活随笔為你收集整理的ASP.NET Core 2.0 全局配置项的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 浅析C#中单点登录的原理和使用
- 下一篇: .NET Core 使用RSA算法 加密