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