Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to convert from .NET Core 5 to .NET Core 6.

In my .NET Core 5, Startup.cs, I have

public class Startup
{
        public IConfiguration Configuration { get; }

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            // ...
            Configuration.GetSection("sectionName")
        }
}

In .NET Core 6, Startup.cs is removed. And from https://learn.microsoft.com/en-us/aspnet/core/migration/50-to-60?view=aspnetcore-6.0&tabs=visual-studio , I don't see how can I read Configuration section from configuration file, appsettings.json.

Can you please point me where I can find example to do that in .NET 6?

like image 268
si Hwang Avatar asked Nov 01 '25 10:11

si Hwang


1 Answers

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.

like image 195
Xinran Shen Avatar answered Nov 04 '25 03:11

Xinran Shen