Home > database >  How can I read the appsettings.json in a .Net 6 console application?
How can I read the appsettings.json in a .Net 6 console application?

Time:04-21

I try to create a .Net 6 Console Application but having troubles reading my appsettings.json file. In a web application I could use this...

var builder = WebApplication.CreateBuilder(args);

But what would I use in a console application? I get this error when trying to add it to program.cs. "The name 'WebApplication' does not exist in the current context"

CodePudding user response:

Add these two nuget packages in your application

Microsoft.Extensions.Configuration

Microsoft.Extensions.Configuration.Json

Then you can use ConfigurationBuilder to use appsettings.json file

var configuration =  new ConfigurationBuilder()
     .SetBasePath(Directory.GetCurrentDirectory())
     .AddJsonFile($"appsettings.json");
            
var config = configuration.Build();
var connectionString = config["ConnectionString"];

Getting Values from AppSettings in Console Application

Adding AppSettings in .net core app

CodePudding user response:

You could use DI to get IConfiguration interface and with it you can access the appsettings.

CodePudding user response:

In a console app I add the appsettings.json and user secrets like this, you may also have a development json file as well.

internal class Program
{
    internal static IConfigurationRoot Configuration;

    public static void Main()
        => new Program().MainAsync().GetAwaiter().GetResult();

    private async Task MainAsync()
    {
        var configurationBuilder = new ConfigurationBuilder();
        configurationBuilder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
        configurationBuilder.AddUserSecrets(typeof(Program).GetTypeInfo().Assembly, optional: false);
        Configuration = configurationBuilder.Build();

        ...
    }
}

Then elsewhere in the console app in any class you can simply call it like this

var someSetting = Program.Configuration["SomeSetting"];

If you want a strongly typed class then see this answer .net core Console application strongly typed Configuration on SO

CodePudding user response:

Link to docs: https://docs.microsoft.com/en-us/dotnet/core/extensions/configuration

Nuget packages needed to doing it:

<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="6.0.0" />

using Microsoft.Extensions.Configuration;

    // Build a config object, using env vars and JSON providers.
    IConfiguration config = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .AddEnvironmentVariables()
        .Build();
    
    // Get values from the config given their key and their target type.
    Settings settings = config.GetRequiredSection("Settings").Get<Settings>();
    
    // Write the values to the console.
    Console.WriteLine($"KeyOne = {settings.KeyOne}");
    Console.WriteLine($"KeyTwo = {settings.KeyTwo}");
    Console.WriteLine($"KeyThree:Message = {settings.KeyThree.Message}");

// Application code which might rely on the config could start here.
// This will output the following:
//   KeyOne = 1
//   KeyTwo = True
//   KeyThree:Message = Oh, that's nice...

JSON File (appsettings.json)

{
    "Settings": {
        "KeyOne": 1,
        "KeyTwo": true,
        "KeyThree": {
            "Message": "Oh, that's nice..."
        }
    }
}

UPD: i checked approach, and its works; My code:

// See https://aka.ms/new-console-template for more information

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;

Console.WriteLine("Hello, World!");
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
IConfiguration c = configurationBuilder.AddJsonFile("appsettings.json").AddEnvironmentVariables().Build();
var k = c.GetRequiredSection("Settings").Get<Settings>().KeyOne;
var n = 1;

public class NestedSettings
{
    public string Message { get; set; } = null!;
}
public class Settings
{
    public int KeyOne { get; set; }
    public bool KeyTwo { get; set; }
    public NestedSettings KeyThree { get; set; } = null!;
}




  • Related