Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

.net 6 how can I get Configuration before the app is build

I am changing my project from .net 5 to .net 6 and have experienced an issue in the program.cs file with the current error of

Cannot modify ServiceCollection after application is built

I am needing to read the configuration before the app is built but the only current way that I know of getting the configuration is after the app is built . This is part of my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var builder = WebApplication.CreateBuilder(args);


// Add builder.Services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddCors();

var app = builder.Build();

IConfiguration configuration = app.Configuration;

var appSettings = new AppSettings(configuration);
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
builder.Services.AddAuthentication(x => // error happens here we have already used builder.Build()
{
    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidAudience = appSettings.Target,
                    ValidIssuer = appSettings.Target
                };
            });

Is there a way of getting IConfiguration before we call builder.Build() ? Since I need the configuration to pass into the class AppSettings which then gets a secret key and allows me to do Authentication on JWT token .

>Solution :

move var app = builder.Build() after authentication configuration.

the .Build() method essentially takes your configuration and gives you a WebApplication that’s built upon the WebApplicationBuilder so you cannot modify the app after it’s been built

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading