How appsettings.json configure application settings, method given Microsoft: https: //docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration
Here is my approach:
Because I created is nothing empty project, a lot of things need to create and references, the new appsettings.json file, and then add a AppSettings field that contains configuration and values
AppSettingsModel.cs create a folder under Models
NuGet package manager writes the following references these packages or project.json
"Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0", "Microsoft.Extensions.Configuration.Json": "1.0.0"
Is then disposed in the 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/