簡體   English   中英

如何使用 ConfigurationBuilder 從 c# 上的 json 配置文件中獲取值?

[英]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參數urlbasePath的值。

我在這里想念什么?

您需要添加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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM