如何在appsettings.json配置應用程序設置,微軟給出的方法:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configurationjson
下面是個人作法:app
由於我創建的是空項目什麼都沒有,好多東西都須要新建和引用,新建appsettings.json文件,而後添加一個AppSettings字段,包含配置和值ui
在Models文件夾下建立一個AppSettingsModel.csspa
NuGet包管理器引用或者在project.json寫入下面這些包3d
"Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
"Microsoft.Extensions.Configuration.Json": "1.0.0"
而後在Startup.cs中配置code
public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddOptions(); services.Configure<AppSettingsModel>(Configuration.GetSection("AppSettings")); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { //這裏的代碼跟主題無關 } }
而後修改一下Controllerblog
public class BasicController : Controller { /// <summary> /// 獲取AccessToken /// </summary> /// <returns></returns> public string GetAccessToken(IOptions<AppSettingsModel> settings) { string accessToken = AccessTokenContainer.TryGetAccessToken(settings.Value.WeixinAppId, settings.Value.WeixinAppSecret); return accessToken; } }
這就算是配置成功了,也能夠看此博主的文章:http://blchen.com/asp-net-read-config-from-appsettings-json/get