How to use appsettings.json in Asp.net core 6 Program.cs file

C#asp.net Core.Net Core.Net 6.0

C# Problem Overview


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 ?

Edited : 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";

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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.

Solution 3 - C#

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....

Solution 4 - C#

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"];
});

//...

Solution 5 - C#

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.

Solution 6 - C#

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/"
}

Solution 7 - C#

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"

Solution 8 - C#

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");

Solution 9 - C#

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": ""
  }

Solution 10 - C#

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");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSajedView Question on Stackoverflow
Solution 1 - C#davidfowlView Answer on Stackoverflow
Solution 2 - C#Mayur EkboteView Answer on Stackoverflow
Solution 3 - C#dimmitsView Answer on Stackoverflow
Solution 4 - C#NkosiView Answer on Stackoverflow
Solution 5 - C#Sangeet AgarwalView Answer on Stackoverflow
Solution 6 - C#Mustafa BazghandiView Answer on Stackoverflow
Solution 7 - C#Abdul KhaliqView Answer on Stackoverflow
Solution 8 - C#Sukesh ChandView Answer on Stackoverflow
Solution 9 - C#Sarwarul RizviView Answer on Stackoverflow
Solution 10 - C#Gerardo VerroneView Answer on Stackoverflow