ASP.NET CORE读取appsettings.json的配置
Posted 小门
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ASP.NET CORE读取appsettings.json的配置相关的知识,希望对你有一定的参考价值。
如何在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/
以上是关于ASP.NET CORE读取appsettings.json的配置的主要内容,如果未能解决你的问题,请参考以下文章
asp.net core 读取appsettings.json
ASP.NET Core读取appsettings.json配置文件信息
ASP.NET CORE读取appsettings.json的配置