[英]Getting appsettings.json settings into an object of class type in .NET Core console application
I wanted to pull the configuration from appsettings.json
into an object of type ExchangeOptions
.我想将配置从
appsettings.json
拉到ExchangeOptions
类型的 object 中。 I know that configuration.Get<T>()
works in ASP.NET Core, but I forgot the correct package for .NET Core Console application.我知道
configuration.Get<T>()
在 ASP.NET 核心中工作,但我忘记了 .NET 核心控制台应用程序的正确 package。 I currently have the following NuGet packages:我目前有以下 NuGet 包:
The example below is pretty self explanatory.下面的示例非常不言自明。
{
"ExchangeConfiguration": {
"Exchange": "Binance",
"ApiKey": "modify",
"SecretKey": "modify"
}
}
using Microsoft.Extensions.Configuration;
using System;
public class ExchangeOptions
{
public Exchange Exchange { get; set; }
public string ApiKey { get; set; }
public string SecretKey { get; set; }
}
class Program
{
static void Main(string[] args)
{
IConfiguration configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
// These work fine
var exchange = configuration["ExchangeConfiguration:Exchange"];
var apiKey = configuration["ExchangeConfiguration:ApiKey"];
var secretKey = configuration["ExchangeConfiguration:SecretKey"];
// This doesn't work, because I don't have the right NuGet package
ExchangeOptions exchangeOptions = configuration.Get<ExchangeOptions>();
Console.ReadKey();
}
}
The correct package for configuration.Get<ExchangeOptions>()
was Microsoft.Extensions.Configuration.Binder
. configuration.Get<ExchangeOptions>()
的正确 package 是Microsoft.Extensions.Configuration.Binder
。 Thanks anyway!不管怎么说,还是要谢谢你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.