How can I read the appsettings.json in a .NET 6 console application?
Asked Answered
H

9

69

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"

Hypoblast answered 21/4, 2022 at 12:11 Comment(7)
See this link: learn.microsoft.com/en-us/aspnet/core/fundamentals/…Justification
Just Add Json file to Configuration : Configuration.AddJson("appsetting.json");Mindimindless
That only mention webb applications like I stated above.Hypoblast
I hope you may get help from this link : #74003369Indecorous
Does this answer your question? How to use appsettings.json in Asp.net core 6 Program.cs fileFertilizer
For a full step by step tutorial, take a look at my SO answer hereAttribution
This is shown very clearly in the official docs with excellent examplesInduration
D
18

Using .NET 6 Console app, try:

using IHost host = Host.CreateDefaultBuilder(args).Build();

IConfiguration config = host.Services.GetRequiredService<IConfiguration>();

string con= config.GetValue<string>("ConnectionStrings:conn1");
//OR
string connectionString = config["ConnectionStrings:conn1"];

Console.WriteLine($"Hello, World! {connectionString}");

appsettings.json (Properties): (CopyToOutputDirectory = Always):

"ConnectionStrings": {
    "conn1": "Server=localhost;Database=MyDatabase;Trusted_Connection=True", 
  }
Downey answered 10/8, 2022 at 2:59 Comment(5)
I am a little confused why this is accepted but unpopular, and how it doesn't reference the JSON file-name.Klopstock
Also IMO secrets like this should not be contained in a json file (esp. if its checked into source control). This is what user secrets is for.Urinate
What is Host in desktop app or console app ?Healing
@Mr.Boy I guess if you are also using Host.CreateApplicationBuilder() for dependency injection stuff, you can use this answer to get IConfiguration via: host.Services.GetRequiredService<IConfiguration>(). Otherwise you can use the other answer which uses ConfigurationBuilder instead.Lashay
Reference of this answer in official docsInduration
P
90

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()
     .AddJsonFile($"appsettings.json");
            
var config = configuration.Build();
var connectionString = config.GetConnectionString("ConnectionString");

Getting Values from AppSettings in Console Application

Adding AppSettings in .net core app

Papst answered 21/4, 2022 at 12:24 Comment(6)
I tried your approach but that does not work. I get "The name 'builder' does not exist in the current context" error?Hypoblast
It will be configuration.Build(); I corrected it in my codePapst
Don't forget to include appsettings.json when building (Properties -> Copy to Output Directory)Bailee
Don't need both nugets. Just Microsoft.Extensions.Configuration.Json because that package implicitly uses Microsoft.Extensions.Configuration already 😎Vicious
i have error: System.IO.FileNotFoundException: "The configuration file 'appsettings.json' was not found and is not optional. The expected physical path was 'C:\work\CheckerHistory\CheckerHistory\CheckerHistory\bin\Debug\net7.0\appsettings.json'." But including appsettings.json when building (Properties -> Copy to Output Directory) helps.Hent
Much simpler way shown in the official docsInduration
C
35

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

Nuget packages are needed to do 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 the approach, and it 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!;
}




Communicate answered 21/4, 2022 at 12:38 Comment(1)
Much simpler way shown in the official docsInduration
D
18

Using .NET 6 Console app, try:

using IHost host = Host.CreateDefaultBuilder(args).Build();

IConfiguration config = host.Services.GetRequiredService<IConfiguration>();

string con= config.GetValue<string>("ConnectionStrings:conn1");
//OR
string connectionString = config["ConnectionStrings:conn1"];

Console.WriteLine($"Hello, World! {connectionString}");

appsettings.json (Properties): (CopyToOutputDirectory = Always):

"ConnectionStrings": {
    "conn1": "Server=localhost;Database=MyDatabase;Trusted_Connection=True", 
  }
Downey answered 10/8, 2022 at 2:59 Comment(5)
I am a little confused why this is accepted but unpopular, and how it doesn't reference the JSON file-name.Klopstock
Also IMO secrets like this should not be contained in a json file (esp. if its checked into source control). This is what user secrets is for.Urinate
What is Host in desktop app or console app ?Healing
@Mr.Boy I guess if you are also using Host.CreateApplicationBuilder() for dependency injection stuff, you can use this answer to get IConfiguration via: host.Services.GetRequiredService<IConfiguration>(). Otherwise you can use the other answer which uses ConfigurationBuilder instead.Lashay
Reference of this answer in official docsInduration
U
6

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

Urinate answered 21/4, 2022 at 12:19 Comment(1)
Main method supports async Task, my advice is to don't use GetAwaiter().GetResult()Phip
M
4

I would prefer the following code because it will automatically read the appsettings.json file from the project directory. Pay attention to _.Configuration I used during configuring DbContext to read the connection string.

var builder = Host.CreateDefaultBuilder(args)
        .ConfigureServices(
                (_, services) => services
                    .AddTransient<IService, Service>()
                    .AddDbContext<ApplicationDbContext>(options =>
                        options.UseNpgsql(
                      _.Configuration.GetConnectionString("DefaultConnection"),
                            b => b.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName)))
                    );
var host = builder.Build();


var dbContext = host.Services.GetRequiredService<ApplicationDbContext>();

I put this together from this link: https://bjdejongblog.nl/net-core-6-dependency-injection-console-program/

Mauser answered 9/10, 2022 at 19:26 Comment(1)
How-to use configuration in library class dependencies?Healing
T
1

Install the following packages

Install-Package Microsoft.Extensions.Configuration.Json
Install-Package Microsoft.Extensions.Hosting

create a file call appsettings.json

{
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "defaultConnection": "data source=.;initial catalog=ExchangeGatewayDb;integrated security=true;MultipleActiveResultSets=True;"
  }
}

add this code to Programe.cs

var hostBuilder = new HostBuilder().ConfigureHostConfiguration(config =>
        {
            config.AddEnvironmentVariables();

            if (args != null)
            {
                config.AddCommandLine(args);
            }
        }).ConfigureAppConfiguration((context, builder) =>
        {
            var env = context.HostingEnvironment;
            builder.SetBasePath(AppContext.BaseDirectory)
            .AddJsonFile("appsettings.json", optional: false)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true).AddEnvironmentVariables();

            var configuration = builder.Build();
            var connectionString = configuration["ConnectionStrings:defaultConnection"];
        }).ConfigureServices(services =>
        {
            services.Configure<ConsoleLifetimeOptions>(opts => opts.SuppressStatusMessages = true);
            //your code
        });

var buildHost = hostBuilder.Build();
buildHost.Run();
Thicken answered 3/10, 2022 at 10:6 Comment(4)
Tried this and the program is always stuck on buildHost.Run()Corinnacorinne
You should do your operation in the ConfigureServices methodThicken
If you make a new .net 6 console application there is no ConfigureServices-method.Corinnacorinne
@esko how-to use with net 6 console?Healing
H
0

I use in my MyApp.Core library, in a ConfigMyApp class:

         public static IConfigurationRoot GetIConfigurationRoot(string outputPath = null)
        {
            var path1 = Directory.GetCurrentDirectory();
            //_configuration =
            var config = new ConfigurationBuilder()
                .SetBasePath(path1)
                .AddJsonFile("appsettings.json").Build();
            return config;
            //return new ConfigurationBuilder()
            //    .SetBasePath(outputPath)
            //    .AddJsonFile("appsettings.json", optional: true)
            //    //.AddUserSecrets("e3dfcccf-0cb3-423a-b302-e3e92e95c128")
            //    .AddEnvironmentVariables()
            //    .Build();
        }

        public static string CONEXION_SQL
        {
            get
            {
                var config = GetIConfigurationRoot();
                return config.GetConnectionString(KeyConexionMyApp);
                //return ConfigurationManager.ConnectionStrings[KeyConexionMyApp].ConnectionString;
            }
        }

Usage:

var myConnectionSQL = ConfigMyApp.CONEXION_SQL;

Use static constructor:

public static partial class ConfigMyApp
{
    static readonly IConfigurationRoot config;
    static ConfigMyApp()
    {
        config = GetIConfigurationRoot();
    }
Healing answered 17/8, 2023 at 11:37 Comment(0)
E
0
  1. you need to create appSetting.json file and set Property Copy Output Directory - copy always

2.write code as below.

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using MidcapERP.Kafka.Configurations;
using MidcapERP.Kafka.Services;

await CreateHostBuilder(args).RunConsoleAsync();

static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
    .ConfigureLogging((hostContext, builder) =>
    {
        builder.ClearProviders(); // This line is optional if you want to clear the default logging providers
        builder.AddConfiguration(hostContext.Configuration.GetSection("Logging"));
        builder.AddConsole();
        builder.AddDebug();
        builder.AddEventSourceLogger();
        builder.SetMinimumLevel(LogLevel.Warning);
    })
    .ConfigureServices((hostContext, services) =>
    {
        services.AddOptions();
        services.Configure<KafkaConfiguration>(hostContext.Configuration.GetSection(nameof(KafkaConfiguration)));
        services.AddHostedService<KafkaConsumerService>();
    })
    .UseConsoleLifetime(); // This line should be the last one
Essam answered 6/9, 2023 at 11:58 Comment(0)
N
0

For console app, we should not use

WebApplication.CreateBuilder(args);

Instead, we should create builder by

var builder = new ConfigurationBuilder();

Add 2 Nuget packages,

  1. Microsoft.Extensions.Configuration.Json
  2. Microsoft.Extensions.Configuration.EnvironmentVariables

then access your app settings by following code,

var builder = new ConfigurationBuilder();
builder.SetBasePath(Directory.GetCurrentDirectory())
   .AddJsonFile("appsettings.json", optional: false, reloadOnChange: 
true);

if you want to override appsettings value by environment, you need to use following,

var builder = new ConfigurationBuilder();
    builder.SetBasePath(Directory.GetCurrentDirectory())
           .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
           .AddEnvironmentVariables("Jai_");
Nebraska answered 26/2 at 5:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.