如何在.Net Core 2.0 App中读取appsettings.json
Posted PowerCoder
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在.Net Core 2.0 App中读取appsettings.json相关的知识,希望对你有一定的参考价值。
This is something that strangely doesn’t seem to be that well documented and took me a while to figure out though in the end it’s pretty simple.
All that’s required is to add the following NuGet packages and an appsettings.json file.
- Microsoft.Extensions.Configuration
- Microsoft.Extensions.Configuration.FileExtensions
- Microsoft.Extensions.Configuration.Json
The appsettings.json files “Copy to Output Directory” property should also be set to “Copy if newer” so that the application is able to access it when published.
The settings are injected in the main method rather than in the startup method as with web apps but the code is essentially the same.
static void Main(string[] args) { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); IConfigurationRoot configuration = builder.Build(); Console.WriteLine(configuration.GetConnectionString("Storage")); Console.WriteLine(configuration.GetSection("ConnectionStrings:Storage").Value); }
In the case of receiving the error “IConfigurationBuilder does not contain a definition for AddJsonFile” just rebuild the project and close and re-open Visual Studio.
以上是关于如何在.Net Core 2.0 App中读取appsettings.json的主要内容,如果未能解决你的问题,请参考以下文章
从.Net Core 2.0 Web应用程序中的apppsettings.json文件中读取值[重复]
.Net Core 2.0+ InfluxDB+Grafana+App Metrics 实现跨平台的实时性能监控
Google App Engine .Net Core 2.0 应用无法访问 Google Cloud SQL 数据库
从 appsettings.json 获取 ConnectionString,而不是在 .NET Core 2.0 App 中硬编码
ASP.NET Core 2.0 中 Web API 的本地用户帐户存储
无法使用 ConfigurationManager 在 C# .NET Core 单元测试项目中读取 app.config