gpt4 book ai didi

asp.net-core - 如何在 .Net Core 中将 App.config 更改为 json 配置文件

转载 作者:行者123 更新时间:2023-12-04 16:33:27 25 4
gpt4 key购买 nike

我的项目使用 App.config 来读取配置属性。例子:
ConfigurationManager.AppSettings["MaxThreads"]
你知道我可以用来从 json 读取配置的库吗?谢谢。

最佳答案

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"));
}

然后,您可以通过将其注入(inject)构造函数来从任何其他地方注入(inject)和访问您的设置类。例如:

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);
}

您可以在 docs 上阅读有关配置的更多信息。或 various blogs

关于asp.net-core - 如何在 .Net Core 中将 App.config 更改为 json 配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38614964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com