mvc_core_config
在.net core mvc中 配置文件格式更改爲json且移除了ConfigurationManager.AppSettings[xmlkey]的方法,
那麼,如何來獲取配置信息呢?
第一步 將json文件添加到應用程序中
<default code>
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
如果是使用默認的方法來啓動的,則可以跳過此步
<reason>
查看源碼 在 CreateDefaultBuilder方法中已使用添加配置文件
//配置信息處理 -- 用於第二步的讀取配置信息
.ConfigureAppConfiguration((Action<WebHostBuilderContext, IConfigurationBuilder>) ((hostingContext, config) =>
{
//注入運行環境
IHostingEnvironment hostingEnvironment = hostingContext.HostingEnvironment;
//加載配置文件
config.AddJsonFile("appsettings.json", true, true).AddJsonFile(string.Format("appsettings.{0}.json", (object) hostingEnvironment.EnvironmentName), true, true);
//根據運行環境加載相應文件
if (hostingEnvironment.IsDevelopment())
{
Assembly assembly = Assembly.Load(new AssemblyName(hostingEnvironment.ApplicationName));
if (assembly != (Assembly) null)
config.AddUserSecrets(assembly, true);
}
config.AddEnvironmentVariables();
if (args == null)
return;
config.AddCommandLine(args);
}))
自定義添加配置文件請參考以上代碼
第二步 讀取配置信息
<code>
<Startup>
//由於在程序啓動時已經配置了configuration 則可以直接通過構造方法獲取配置信息
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
第三步 在Controller 獲取配置信息
<code>
<Startup>
<method --> ConfigureServices>
//添加選項
services.AddOptions();
//將配置信息進行DI注入
services.Configure<AppSetting>(Configuration.GetSection(nameof(AppSetting)));
<相關方法說明>
GetSection:
key-value 取值
類似於Dictionary取值的操作
Configure:
進行DI注入
關鍵性代碼:
//進行DI注入 AddSingleton 全局共享一個 IOptionsChangeTokenSource<TOptions> 注入參數對應的type
services.AddSingleton<IConfigureOptions<TOptions>>((IConfigureOptions<TOptions>) new NamedConfigureFromConfigurationOptions<TOptions>(name, config))
即實際上還是利用AddSingleton注入實現
<source code>
/// <summary>
/// Registers a configuration instance which TOptions will bind against. 將配置實例作爲option綁定到參數上
/// </summary>
/// <typeparam name="TOptions">The type of options being configured.</typeparam>
/// <param name="services">The <see cref="T:Microsoft.Extensions.DependencyInjection.IServiceCollection" /> to add the services to.</param>
/// <param name="config">The configuration being bound.</param>
/// <returns>The <see cref="T:Microsoft.Extensions.DependencyInjection.IServiceCollection" /> so that additional calls can be chained.</returns>
public static IServiceCollection Configure<TOptions>(this IServiceCollection services, IConfiguration config) where TOptions : class
{
return services.Configure<TOptions>(Microsoft.Extensions.Options.Options.DefaultName, config);
}
/// <summary>
/// Registers a configuration instance which TOptions will bind against.同上
/// </summary>
/// <typeparam name="TOptions">The type of options being configured.</typeparam>
/// <param name="services">The <see cref="T:Microsoft.Extensions.DependencyInjection.IServiceCollection" /> to add the services to.</param>
/// <param name="name">The name of the options instance.</param>
/// <param name="config">The configuration being bound.</param>
/// <returns>The <see cref="T:Microsoft.Extensions.DependencyInjection.IServiceCollection" /> so that additional calls can be chained.</returns>
public static IServiceCollection Configure<TOptions>(this IServiceCollection services, string name, IConfiguration config) where TOptions : class
{
if (services == null)
throw new ArgumentNullException(nameof (services));
if (config == null)
throw new ArgumentNullException(nameof (config));
//進行DI注入 AddSingleton 全局共享一個 IOptionsChangeTokenSource<TOptions> 注入參數對應的type
services.AddSingleton<IOptionsChangeTokenSource<TOptions>>((IOptionsChangeTokenSource<TOptions>) new ConfigurationChangeTokenSource<TOptions>(name, config));
return services.AddSingleton<IConfigureOptions<TOptions>>((IConfigureOptions<TOptions>) new NamedConfigureFromConfigurationOptions<TOptions>(name, config));
}
<Controller>
public abstract class BaseController : Controller
{
protected AppSetting AppSetting { get; set; }
protected BaseController(IOptions<AppSetting> option) => AppSetting = option.Value;
}
intro:由於在mvc經常會使用配置信息,於是我便將獲取配置信息的相關處理封裝在一個抽象控制器中,故只需要在使用配置信息的控制器中繼承此控制器即可
然後就可以在控制器中通過AppSetting獲取配置信息了
擴展說明
在Startup中直接獲取配置文件:
public Startup(IApplicationEnvironment appEnv, IHostingEnvironment env) {
_config = new ConfigurationBuilder()
.AddJsonFile("config.json")
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables()
.Build();
}
[https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.1&tabs=basicconfiguration](https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.1&tabs=basicconfiguration "官方教程")
補充說明:
看見很多人說配置信息的獲取不能實時更新,其實只是應用方式錯了罷了
通過查看源碼可以知道
《source code》
services.AddSingleton<IOptionsChangeTokenSource<TOptions>>((IOptionsChangeTokenSource<TOptions>) new ConfigurationChangeTokenSource<TOptions>(name, config));
微軟實際上是有采用修改監聽的
故只需要將我們控制構造中的IOptions<> 替換爲 IOptionsMonitor<>即可實時讀取配置信息
//讀取最新值
IOptionsMonitor<>.CurrentValue
IOptionsMonitor
定義:解析
//獲取最新值
TOptions CurrentValue { get; }
//通過given name獲取值
TOptions Get(string name);
//當值發送改變時觸發
IDisposable OnChange(Action<TOptions, string> listener);
通過定義可知IOptionsMonitor是一個類似於監聽器的存在
所以應該就是通過這個來實時進行更新的
備註:其中使用的AppSetting 即 我配置信息對應的實體類 【可根據實際情況進行命名】
歡迎各位大佬評論並指出我的錯誤 :)
author:monster
since:6/4/2018 11:12:45 AM
direction:.net core 2.0 mvc 配置文件的使用