作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的项目使用 App.config 来读取配置属性。例子:
你知道我可以用来从 json 读取配置的库吗?谢谢。
ConfigurationManager.AppSettings["MaxThreads"]
最佳答案
ConfigurationManager
静态类在 ASP.NET Core 中通常不可用。相反,您应该使用新的 ConfigurationBuilder
系统和强类型配置。
例如,默认情况下,您的Startup
中会建立一个配置。使用类似于以下内容的类:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
appsettings.json
加载配置。文件并将 key 附加到配置根目录。如果您有如下的 appsettings 文件:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"ThreadSettings" : {
"MaxThreads" : 4
}
}
ThreadSettings
类似于以下的类:
public class ThreadSettings
{
public int MaxThreads {get; set;}
}
Configure
将此强类型设置类绑定(bind)到您的配置。方法到您的
ConfigureServices
方法。
using Microsoft.Extensions.Configuration;
public void ConfigureServices(IServiceCollection services)
{
services.Configure<ThreadSettings>(Configuration.GetSection("ThreadSettings"));
}
public class MyFatController
{
private readonly int _maxThreads;
public MyFatController(ThreadSettings settings)
{
maxThreads = settings.MaxThreads;
}
}
ConfigureServices
中注入(inject)它。使其在您的类(class)中可用。
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(Configuration);
}
关于asp.net-core - 如何在 .Net Core 中将 App.config 更改为 json 配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38614964/
我是一名优秀的程序员,十分优秀!