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

來源:互聯網
上載者:User

標籤:settings   containe   one   hang   bsp   als   mode   ons   access   

如何在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的配置

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.