ASP.NET Core 6 How to Access Configuration During Startup

ASP.NET Core 6 how to access Configuration during startup

WebApplicationBuilder returned by WebApplication.CreateBuilder(args) exposes Configuration and Environment properties:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
...
ConfigurationManager configuration = builder.Configuration; // allows both to access and to set up the config
IWebHostEnvironment environment = builder.Environment;

WebApplication returned by WebApplicationBuilder.Build() also exposes Configuration and Environment:

var app = builder.Build();
IConfiguration configuration = app.Configuration;
IWebHostEnvironment environment = app.Environment;

Also check the migration guide and code samples.

How to inject IConfiguration in asp.net core 6

The IConfiguration can be accessed in the WebApplicationBuilder.

Sample Image

So no need to inject IConfiguration any more, it is now a property in the builder in Program.cs.
Sample Image

var builder = WebApplication.CreateBuilder(args);
var config = builder.Configuration;

builder.Services.AddInfrastructureServices(config);
builder.Services.AddPersistenceServices(config);

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

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.

What's the best method to access configuration in .NET 6?

You can refer to this simple demo to learn about how to

create a class that represents your settings and then bind the configuration to an instance of that class type

The values in appsetting.json:

"UserCred": {
"Username":"Jack",
"Password":"123"
},

Create a model class:

public class User
{
public string Username { get; set; }
public string Password { get; set; }
}

Configure in your programs.cs:

builder.Services.Configure<User>(builder.Configuration.GetSection("UserCred"));

In the controller, use DI to inject it, then you can get the model with value:

public class HomeController : Controller
{
private readonly IOptions<User> _configuration;

public HomeController(IOptions<User> configuration)
{
_configuration = configuration;
}

//.......
}

Sample Image

What's the benefit?

For me, if there are many data ​​in appsetting.json, Creating a class to map them only needs to map once, You don't need to get them one by one, which makes coding more convenient.

.NET 6 (stable) IConfiguration setup in Program.cs

  1. Switching to minimal hosting model is not required, you can still use the generic hosting (the one with startup).

It seems that the Microsoft.Extensions.Configuration isn't even used!

The using Microsoft.Extensions.Configuration; directive is not needed cause new feature global using statements is heavily utilized in .NET 6 templates.

3.

var Configuration = builder.Configuration;

The Program file in the new templates is using another relatively new feature (C# 9) - top-level statements, so the var Configuration is just a variable accessible only inside the generated Main method.

4.

secret = Startup.Configuration["GoogleRecaptchaV3:Secret"];

You can access this value inside the top-level statement file via:

var secret = builder.Configuration["GoogleRecaptchaV3:Secret"];

To make settings accessible outside that file (or Startup in generic hosting) I highly recommend to use DI (as shown in the docs here or here).

In case if you have A LOT of code relying on static configuration being available and you need a quick temporary fix you can add partial Program class at the end of the top-level statement file and do something like:

// ....
WebApplication app = builder.Build();
Configuration = app.Configuration;
// ...

public partial class Program
{
internal static IConfiguration Configuration { get; private set; }
}

But I highly recommend against that.

How to convert `Configuration.GetSection` from .NET Core 5 to .NET Core 6?

In .Net 6 , Configuration has been configured in Program.cs, You just need to use:

var builder = WebApplication.CreateBuilder(args);
//.......
builder.Services.Configure<Your model>(configuration.GetSection("sectionName"));

to Map appSettings.json object to class.

Or you can just use:

var builder = WebApplication.CreateBuilder(args);
//.......
builder.Configuration.GetSection("sectionName")

to read the value in appsetting.json.

ASP.NET Core Configuration Section in Startup

Updated Answer
For ASP Core 1.1.0 generic model binding is now done using Get:

var config = Configuration.GetSection("configuredClients").Get<ClientConfiguration>();

Original Answer
How about this:

var config = Configuration.GetSection("configuredClients").Bind<ClientConfiguration>();

How do I access Configuration in any class in ASP.NET Core?

Update

Using ASP.NET Core 2.0 will automatically add the IConfiguration instance of your application in the dependency injection container. This also works in conjunction with ConfigureAppConfiguration on the WebHostBuilder.

For example:

public static void Main(string[] args)
{
var host = WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(builder =>
{
builder.AddIniFile("foo.ini");
})
.UseStartup<Startup>()
.Build();

host.Run();
}

It's just as easy as adding the IConfiguration instance to the service collection as a singleton object in ConfigureServices:

public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IConfiguration>(Configuration);

// ...
}

Where Configuration is the instance in your Startup class.

This allows you to inject IConfiguration in any controller or service:

public class HomeController
{
public HomeController(IConfiguration configuration)
{
// Use IConfiguration instance
}
}

How to read configuration settings before initializing a Host in ASP .NET Core?

You can clear the default sources added by CreateDefaultBuilder then add a pre-built IConfiguration with the AddConfiguration extension method.

public static void Main(string[] args)
{
//...

var configuration = new ConfigurationBuilder()
.AddEnvironmentVariables()
.AddCommandLine(args)
.AddJsonFile("appsettings.json")
.Build();

//Do something useful with the configuration...

var host = Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(builder =>
{
builder.Sources.Clear();
builder.AddConfiguration(configuration);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.Build();

//...
}

.Net 6 core: How to inject a configuration to the controller?

error message is too clear:

An object reference is required for the nonstatic field, method, or
property 'member'

you should send IConfiguration as parameter to static method.

private static JwtSecurityToken GetToken(List<Claim> authClaims, IConfiguration config)
{
var key = config["Jwt:Key"];
}

while using:

public IActionResult Get(){
var claims = GetClaims();
var token = GetToken(claims, _ config)
}


Related Topics



Leave a reply



Submit