ASP.NET CORE读取appsettings.json的配置

如何在appsettings.json配置应用程序设置,微软给出的方法:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration

下面是我的做法:

因为我建立的是空项目什么都没有,好多东西都需要新建和引用,新建appsettings.json文件,然后添加一个AppSettings字段,包含配置和值

ASP.NET CORE读取appsettings.json的配置

 

在Models文件夹下创建一个AppSettingsModel.cs

ASP.NET CORE读取appsettings.json的配置

 

NuGet包管理器引用或者在project.json写入下面这些包

    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0"

 

然后在Startup.cs中配置

ASP.NET CORE读取appsettings.json的配置
    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)
        {
        //这里的代码跟主题无关
        }
    }
ASP.NET CORE读取appsettings.json的配置

 

然后修改一下Controller

ASP.NET CORE读取appsettings.json的配置
    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;
        }
    }
ASP.NET CORE读取appsettings.json的配置

 

这就算是配置成功了,也可以看此博主的文章:http://blchen.com/asp-net-read-config-from-appsettings-json/

ASP.NET CORE读取appsettings.json的配置

上一篇:Android性能优化---基础知识


下一篇:Android使用gradle依赖管理、依赖冲突终极解决方案(转)