如何在appsettings.json配置应用程序设置,微软给出的方法:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration
下面是我的做法:
因为我建立的是空项目什么都没有,好多东西都需要新建和引用,新建appsettings.json文件,然后添加一个AppSettings字段,包含配置和值
在Models文件夹下创建一个AppSettingsModel.cs
NuGet包管理器引用或者在project.json写入下面这些包
"Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
"Microsoft.Extensions.Configuration.Json": "1.0.0"
然后在Startup.cs中配置
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) { //这里的代码跟主题无关 } }
然后修改一下Controller
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/