157

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

15 Answers 15

138

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

5
  • 18
    This should be marked as the correct Answare for .NET Core 6 that comes just with minimal startup.cs class. Many thanks for your examples!! Feb 25, 2022 at 20:42
  • 1
    I agree that this is the answer. I intentionally logged in to stackoverflow to vote this answer up! Jul 12, 2022 at 8:02
  • is it case sensitive?
    – Berkay
    Jun 6 at 16:31
  • Not case sensitive. github.com/dotnet/runtime/blob/…
    – GGleGrand
    Jun 11 at 19:47
  • I use Desktop Windows Forms app or Console app. How-to use it?
    – Kiquenet
    Aug 17 at 10:58
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.

4
  • 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, 2022 at 10:36
  • What are you asking exactly?
    – davidfowl
    May 30, 2022 at 6: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, 2022 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, 2022 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.
6
  • This doesn't work in .NET 6. AddDbContext doesn't exist. Is there a missing using?
    – dvallejo
    Jan 11, 2022 at 1:39
  • 1
    I agree this doesn't work in NET 6. AddJsonFile method is not a part of the ConfigurationBuilder class. Feb 25, 2022 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, 2022 at 10:12
  • 3
    It worked but I needed to add the NuGet packets manually first in .NET Core 6. <PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="6.0.1" /> <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="6.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" /> Mar 1, 2022 at 9:59
  • You should only need this package: Microsoft.Extensions.Configuration.Json. If you want to use AddJsonFile that is.
    – N-ate
    Jul 5, 2022 at 2:06
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"];
});

//...
4
27

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;
}
0
17

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.

1
  • 3
    thanks for showing builder.Configuration.GetSection(). that's what i was looking for!
    – symbiont
    Feb 16, 2022 at 13:44
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"
1
  • 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 4, 2022 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/"
}
1
  • 1
    I was going to add an answer about referencing builder.Configuration. Good shout!
    – psiodrake
    Apr 19, 2022 at 11:47
8

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

1
  • The no main() really did my head in! Sep 20, 2022 at 21:22
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");
1
  • 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. Feb 25, 2022 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"];
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");
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": ""
  }
3
  • This should be marked as the correct Answare for .NET Core 6 that comes with just the minimal program.cs class. Many thanks for your examples! Feb 25, 2022 at 21:22
  • 1
    'builder' does not exist in the current context
    – Fandango68
    Jun 8, 2022 at 1:57
  • This always comes up null. Any ideas on how to make this work in Dotnet6.0?
    – MC9000
    Jul 26 at 15:47
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": "[email protected]",
        "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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.