![](/img/trans.png)
[英]How do I get the key and it's object from a JSON file in c# using JSON.net?
[英]How do I get values from a json configuration file on c# using ConfigurationBuilder?
我正在嘗試從以下notificatorConfig.json
文件中獲取路徑 url :
{
"UserNotificatorConfig": {
"URL": "http://localhost:8001",
"BasePath": "/send-message/android"
}
}
使用ConfigurationBuilder()
如下:
public async Task Send(string message)
{
var config = new ConfigurationBuilder()
.AddJsonFile("notificatorConfig.json", true)
.Build();
var url = config.GetSection("UserNotificatorConfig:URL").Value;
var basePath = config.GetSection("UserNotificatorConfig:BasePath").Value;
await _rest.PostAsync<Notification>(url, basePath, message);
}
我的json
文件和我的Send()
方法所在的文件都在同一個文件夾中。
但是每次我嘗試在單元測試中調試此方法時,我都會得到null
參數url
和basePath
的值。
我在這里想念什么?
您需要添加SetBasePath(Directory.GetCurrentDirectory())
:
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("notificatorConfig.json", true)
.Build();
而且,正如@Dennis1679 所說,您應該在啟動時構建配置。
編輯:
如果這沒有幫助,請以這種方式訪問Section
內的Value
:
var userNotificatorConfig = config.GetSection("UserNotificatorConfig");
var url = userNotificatorConfig.GetValue<string>("URL");
var basePath = userNotificatorConfig.GetValue<string>("BasePath");
而不是這種方式:
var url = config.GetSection("UserNotificatorConfig:URL").Value;
var basePath = config.GetSection("UserNotificatorConfig:BasePath").Value;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.