153

I'm trying to access appsettings.json in my Asp.net core v6 application Program.cs file, but in this version of .Net the Startup class and Program class are merged together and the using and another statements are simplified and removed from Program.cs. In this situation, How to access IConfiguration or how to use dependency injection for example ?

Code

Here is my default Program.cs that Asp.net 6 created for me

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "localhost:6379";
});

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new() { Title = "BasketAPI", Version = "v1" });
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "BasketAPI v1"));
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

For example , I want to use appsettings.json instead of hard typed connectionstring in this line :

options.Configuration = "localhost:6379";
ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
Sajed
  • 1,797
  • 2
  • 7
  • 21
  • That file is already loaded by default. Is the real question how to access `Configuration`? – Panagiotis Kanavos Oct 01 '21 at 11:07
  • 3
    In .net version 6 there is no Startup.cs and Program.cs and Startup.cs are merged together in Program.cs file and in this new situation, there is no Configuration created by default and we can't inject it @PanagiotisKanavos – Sajed Oct 04 '21 at 13:49
  • 1
    Does this answer your question? [How can I read the appsettings.json in a .Net 6 console application?](https://stackoverflow.com/questions/71954271/how-can-i-read-the-appsettings-json-in-a-net-6-console-application) – Michael Freidgeim Mar 18 '23 at 06:51

15 Answers15

131

In case that we have in appsettings

"settings": {
    "url": "myurl",
    "username": "guest",
    "password": "guest"
  }

and we have the class

public class Settings
    {
        public string Url { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
    }

we can use also

var settings = builder.Configuration.GetSection("Settings").Get<Settings>();

var url = settings.Url;

etc....

Tony Dong
  • 3,213
  • 1
  • 29
  • 32
dimmits
  • 1,999
  • 3
  • 12
  • 30
95

While the examples above work, the way to do this is the following:

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = builder.Configuration["Redis"];
});

The WebApplicationBuilder has a configuration object as a property that you can use.

davidfowl
  • 37,120
  • 7
  • 93
  • 103
  • Suppose in the dev json file I created key called `key1` and in prod json file I create key called `key2`, then when I run the project in visual studio, it is reading both the keys. Shouldn't it read only the key from the dev json file? – variable Jan 12 '22 at 10:36
  • What are you asking exactly? – davidfowl May 30 '22 at 06:48
  • So using a console application with a program.cs. I cannot for the life of me get this to work. I've tried adding namespaces NuGet package and nothing seems to recognize WebApplication. var builder = WebApplication.CreateBuilder(args); – AndyMan Jun 22 '22 at 16:32
  • 2
    Use an empty web project. If you want to get access to ASP.NET APIs in a console app then you need to add a FrameworkReference to Microsoft.AspNetCore.App – davidfowl Jun 24 '22 at 11:15
38

appsettings.json is included by default, you can use it directly. If you want to include files explicitly, you can include them like this

builder.Configuration.AddJsonFile("errorcodes.json", false, true);

And dependency injection like this

builder.Services.AddDbContext<>() // like you would in older .net core projects.
Mayur Ekbote
  • 1,700
  • 1
  • 11
  • 14
  • This doesn't work in .NET 6. AddDbContext doesn't exist. Is there a missing using? – dvallejo Jan 11 '22 at 01:39
  • 1
    I agree this doesn't work in NET 6. AddJsonFile method is not a part of the ConfigurationBuilder class. – Oliver Nilsen Feb 25 '22 at 11:12
  • 1
    @OliverNilsen it definitely is. you can test that by 'var config = new ConfigurationBuilder().AddJsonFile("x.json").Build();' and you can do the same with builder.Configuration.AddJsonFile(...) as mentioned by Mayur Ekbote – Bandook Feb 26 '22 at 10:12
  • 3
    It worked but I needed to add the NuGet packets manually first in .NET Core 6. – Oliver Nilsen Mar 01 '22 at 09:59
  • You should only need this package: Microsoft.Extensions.Configuration.Json. If you want to use AddJsonFile that is. – N-ate Jul 05 '22 at 02:06
  • I would have marked this as accepted answer. – Vish Jul 23 '22 at 18:45
31

Assuming an appsettings.json

{
    "RedisCacheOptions" : {
        "Configuration": "localhost:6379"
    }
}

There is nothing stopping you from building a configuration object to extract the desired settings.

IConfiguration configuration = new ConfigurationBuilder()
                            .AddJsonFile("appsettings.json")
                            .Build();

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddStackExchangeRedisCache(options => {
    options.Configuration = configuration["RedisCacheOptions:Configuration"];
});

//...
Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • Yeah it's a good way to build it, in older versions we were injecting the configuration instead of building it in Startup.cs – Sajed Sep 30 '21 at 11:16
  • What is 'WebApplication'? Project name? – Fandango68 Jun 08 '22 at 01:51
  • @Fandango68 Check out documentation here https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.webapplication – Nkosi Jun 08 '22 at 02:35
  • Actually I found out this solution is for web apps. Mine is a console app. My solution was here https://stackoverflow.com/questions/71954271/how-can-i-read-the-appsettings-json-in-a-net-6-console-application – Fandango68 Jun 08 '22 at 02:59
24

Retrieve appsettings.json section values via Injection

appsettings.json section:

{
  "AppSettings": {
    "Key": "Value"
  }
}

AppSettings.cs:

public class AppSettings
{
    public string Key { get; set; }
}

Program.cs:

builder.Services.AddOptions();
builder.Services.Configure<AppSettings>(
    builder.Configuration.GetSection("AppSettings"));

Inject IOptions<> via constructor:

private readonly AppSettings _appSettings;

public HomeController(
    IOptions<AppSettings> options)
{
    _appSettings = options.Value;
}
John Deer
  • 2,033
  • 2
  • 13
  • 16
15

Create a class:

public class RedisCacheOptions
{
    public string Configuration { get; set; }
}

And then, in your program.cs, do the following:

var redisCacheOptions = new RedisCacheOptions();
builder.Configuration.GetSection(nameof(RedisCacheOptions)).Bind(redisCacheOptions);

You can now access the configuration info by simply saying:

redisCacheOptions.Configuration

Now say you had a nested structure in appSettings.json like so:

"AuthenticationConfiguration": {
  "JwtBearerConfiguration": {
    "Authority": "https://securetoken.google.com/somevalue",
    "TokenValidationConfiguration": {
      "Issuer": "https://securetoken.google.com/somevalue",
      "Audience": "somevalue"
    }
  }
}

Then, your class structure would be something like:

public class AuthenticationConfiguration
{
    public JwtBearerConfiguration JwtBearerConfiguration { get; set; } = new JwtBearerConfiguration();
}

public class JwtBearerConfiguration
{
    public string Authority { get; set; }

    public TokenValidationConfiguration TokenValidationConfiguration { get; set; } =
        new TokenValidationConfiguration();
}

public class TokenValidationConfiguration
{
    public string Issuer { get; set; }
    public string Audience { get; set; }
}

With this, if you were to do:

var authConf = new AuthenticationConfiguration();
builder.Configuration.GetSection(nameof(AuthenticationConfiguration)).Bind(authConf);

Then in your program, you could access values as:

AuthenticationConfiguration.JwtBearerConfiguration.Authority

This approach allows you to do away with magic strings, plus you get IntelliSense, so it's a win-win.

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
Sangeet Agarwal
  • 1,674
  • 16
  • 25
8

Solved: Get appsetting value in program.css in dotnet6

appsettings.json

  "AllowedHosts": "*",
  "ServiceUrls": {
  "EmployeeAPI": "https://localhost:44377/" },

Program.cs

var builder = WebApplication.CreateBuilder(args);    
var provider = builder.Services.BuildServiceProvider();
var configuration = provider.GetService<IConfiguration>();
SD.EmployeeAPIBase = configuration.GetValue<string>("ServiceUrls:EmployeeAPI");

Class static variable:

public static class SD //Static Details
{
    public static string EmployeeAPIBase { get; set; }     
}

Finally, use the full URL

URL = SD.EmployeeAPIBase + "api/EmpContact/GetGovernates"
Abdul Khaliq
  • 2,139
  • 4
  • 27
  • 31
  • I have similar situation but these code is not working, In my code at the program.cs the value is remain null. Can you please refer full code. – Vipin Jha Jul 04 '22 at 20:28
8

In Program.cs, try this code:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

ConfigurationManager configuration = builder.Configuration;

var rabbitMQSection = configuration.GetSection("RabbitMQ");
var rabbitMQConnectionUrl = rabbitMQSection["ConnectionUrl"];

where the appsettings.json file is:

"AllowedHosts": "*",
"RabbitMQ": {
    "ConnectionUrl": "amqp://guest:guest@localhost:5672/"
}
MB_18
  • 1,620
  • 23
  • 37
7

Since my application was a consol .NET Core 6 application, I had to install a nuget packages first:

  • Microsoft.Extensions.Hosting
  • Microsoft.Extensions.Configuration

Then add their associated usings:

  • using Microsoft.Extensions.Hosting;
  • using Microsoft.Extensions.Configuration;

Then I added this code to the Program.cs file

// Build a config object, using env vars and JSON providers.
IConfiguration config = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .AddEnvironmentVariables()
    .Build();
Settings settings = config.GetRequiredSection("Settings").Get<Settings>();

I have a Settings.cs class to accept the values from my appsettings.json file

Settings.cs

internal class Settings
{
    public static string Setting1 { get; set; }
    public static string Setting2 { get; set; }
    public static string Setting3 { get; set; }

}

And AppSettings.json

"Settings": {
    "Setting1": "yep",
    "Setting2": "nope",
    "Setting3": "kjkj"
  }

This resource from Microsoft helped me navigate the new .NET Core 6 architecture

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

AlignedDev
  • 8,102
  • 9
  • 56
  • 91
KirstieBallance
  • 1,238
  • 12
  • 26
4

In .NET 6

appSettings.json

{
  "Authentication": {
    "CookieAuthentication": {
      "LoginPath": "/Security/Login"
    }
  },
  "TestValue" :  "Testing data"
}

Program.cs

var builder = WebApplication.CreateBuilder(args);

var testValue = builder.Configuration.GetValue<string>("TestValue");

var cookieAuthenticationLoginPath = builder.Configuration.GetValue<string>("Authentication:CookieAuthentication:LoginPath");
Sukesh Chand
  • 2,339
  • 2
  • 21
  • 29
  • Even if this works fine, the approach of @dimmits described below does not use the CreateBuilder phase and it might be more performant as the builder is already in place when you create the app. – Gerardo Verrone Feb 25 '22 at 20:39
4

This is how you can get appsettings.json values in Program.cs file. Here is sample

appsettings.json file

  "Jwt": {
    "Key": "ThisismySecretKey",
    "Issuer": "www.joydipkanjilal.net"
  },

Get values in Program.cs file

var app = builder.Build();
var config = app.Configuration;
var key = config["Jwt:Key"];
var issuer = config["Jwt:Issuer"];
R15
  • 13,982
  • 14
  • 97
  • 173
2

In addition to the @dimmits & @Sarwarul Rizvi answares, if you would like to read a plain key value pair instead to map to a complex object, you can use:

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Information",
      "Microsoft.AspNetCore.SpaProxy": "Information",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedOrigins": "https://localhost:444/YourApplicationUri;https://localhost:7211",
  "ConnectionStrings": {
    "Default": "Connection String details"
  }
}

program.cs

ConfigurationManager configuration = builder.Configuration;
var allowedOrigins = configuration.GetValue<string>("AllowedOrigins");

This can be used for example to config Cors

if (!String.IsNullOrEmpty(allowedOrigins))
{
    builder.Services.AddCors(options =>
    {
        var origins = allowedOrigins.Split(";");

        options.AddPolicy("CorsPolicy", policy =>
        {
            policy.AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials()
                .WithOrigins(origins);
        });
    });
}

Later and below app.UseRouting();

app.UseCors("CorsPolicy");
Gerardo Verrone
  • 361
  • 4
  • 7
2

You can use this method

builder.Configuration.GetConnectionString("<connection string name>");
1

You can read the setting value from your appsettings.json file like this, in Program.cs:

var dbConnectionString = builder.Configuration.GetSection("ConnectionStrings:TestDbConnection").Value;

Considering the setting looks something like this in your appsettings.json file:

  "ConnectionStrings": {
    "TestDbConnection": ""
  }
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
1
You can also do this with the following approach. Exemplified below
    **appsettings.json**
    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "AllowedHosts": "*",
      "AppSettings": {
        "dbConnection": "Data Source=myServerName;Initial Catalog=dbName;persist security info=True;User Id=userId;Password=testPWD;MultipleActiveResultSets=True",
        "sendereMail": "test@testdomain.com",
        "MQDetails": {
          "hostName": "testHost",
          "username": "testUser",
          "passWord": "testPwd",
          "exchangeName": "testName"
        }
      }
    }
    **AppSettings.cs**
        public class AppSettings
        {
            public string? dbConnection { get; set; }
            public string? sendereMail { get; set; }
            public Dictionary<string, string>? MQDetails { get; set; }
        }
**IDemoService.cs**
public interface IDemoService
    {
        string DemoMessage(string name);
    }
**DemoService.cs**
public class DemoService:IDemoService
    {
        public string DemoMessage(string name)
        {
            return "Welcome to you " + name;
        }
    }
    **GetConfigurationsController.cs**
    namespace DotNet6.Controller
    {
        [Route("api/[controller]")]
        [ApiController]
        public class GetConfigurationsController : ControllerBase
        {
            private readonly AppSettings appSettings;
            private readonly IDemoService _demoService;
            public GetConfigurationsController(IOptions<AppSettings> options,IDemoService demoService)
            {
                appSettings = options.Value;
                _demoService = demoService;
            }
    
            [HttpGet("appsettings")]
            public AppSettings Get()
            {
    
                return appSettings;
            }
        [HttpGet("GetMessage")]
        public string GetMessage()
        {
    
            return _demoService.DemoMessage("Barbie");
        }
        }
    }

    **Program.cs**
    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    builder.Services.AddRazorPages();
    builder.Services.AddControllers();
    builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings"));
    
    builder.Services.AddConnections();
    builder.Services.AddSingleton<IDemoService, DemoService>();
    
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen(options =>
    {
        //The generated Swagger JSON file will have these properties.
        options.SwaggerDoc("v1", new OpenApiInfo
        {
            Title = "My API POC",
            Version = "v1",
        });
    });
    
    
    var app = builder.Build();
    
    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyPOC");
            c.RoutePrefix = string.Empty;
        });
        app.UseExceptionHandler("/Error");
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    
    app.UseRouting();
    
    app.UseAuthorization();
    
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
        endpoints.MapControllers();
    });
    
    app.Run();

enter image description here enter image description here

Govind
  • 186
  • 5