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 的新手,也是依赖注入等
在您想要读取值的类库中,您应该能够使用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
归档时间: |
|
查看次数: |
12989 次 |
最近记录: |