简体   繁体   中英

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://docs.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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM