简体   繁体   中英

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 . I know that configuration.Get<T>() works in ASP.NET Core, but I forgot the correct package for .NET Core Console application. I currently have the following NuGet packages:

  • Microsoft.Extensions.Configuration
  • Microsoft.Extensions.Configuration.FileExtensions
  • Microsoft.Extensions.Configuration.Json

The example below is pretty self explanatory.

appsettings.json

{
  "ExchangeConfiguration": {
    "Exchange": "Binance",
    "ApiKey": "modify",
    "SecretKey": "modify"
  }
}

Program.cs

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 . Thanks anyway!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM