.net-core - 如何在 dot net core 项目中使用 IConfiguration 访问自定义 JSON 文件?
问题描述
我有一个 json 文件 creds.json 作为
我正在使用 IConfiguration 读取 creds.json 使用以下内容:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, configuration) =>
{
configuration.AddJsonFile("creds.json", optional: true, reloadOnChange: true);
}
我的疑问是:在我的项目中注入 creds.json 文件后,如何访问它并读取用户名和密码值?
谢谢。
解决方案
public class VaultController : ControllerBase
{
public IConfiguration Configuration { get; }
public VaultController(IConfiguration configuration)
{
Configuration = configuration;
}
[HttpGet("/api/readVault")]
public string GetVaultDetails()
{
var Username = Configuration.GetValue<string>("username");
var Password = Configuration.GetValue<string>("password");
str = "name is:" + Username + " password is:" + Password;
return str;
}
}