.NET 6.0 - 从类库读取 appsettings.json 值

dev*_*dev 11 .net-core .net-6.0

.NET 6.0 - 从类库获取 appsettings.json 值。我有一个 .NET 6.0 Web api 项目,另一个是类库。

我想将一些设置读入类库。

我们在 Web api 项目中有 appsettings.json。如何读取类库中的这些值?

您能给我提供正确的代码片段吗

我是 .net core 6 的新手,也是依赖注入等

mnc*_*mnc 4

在您想要读取值的类库中,您应该能够使用ConfigurationBuilder. 首先,定义 appsettings.json 的位置:

string filePath = @"C:\MyDir\MySubDirWhereAppSettingsIsLocated\appSettings.json"; //this is where appSettings.json is located

filePath然后在尝试访问文件时使用:

IConfiguration myConfig = new ConfigurationBuilder()
   .SetBasePath(Path.GetDirectoryName(filePath))
   .AddJsonFile("appSettings.json")
   .Build();
Run Code Online (Sandbox Code Playgroud)

然后,您可以appsettings.json像这样访问内部的各个值:

string myValue = myConfig.GetValue<string>("nameOfMyValue");

请注意,您需要导入 NuGet 包Microsoft.Extensions.Configuration.Json

  • 我认为,一般来说,您应该避免读取类库项目中的设置,而是公开一些 API 以将解析后的设置传递给库。 (5认同)