繁体   English   中英

".net 6 如何在构建应用程序之前获取配置"

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

我正在将我的项目从 .net 5 更改为 .net 6,并且在 program.cs 文件中遇到问题,当前错误为

构建应用程序后无法修改 ServiceCollection<\/strong>

我需要在构建应用程序之前读取配置,但我知道获取配置的唯一当前方法是在构建应用程序之后。 这是我的代码的一部分:

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
                };
            });

在身份验证配置后移动var app = builder.Build()<\/code> 。

.Build()<\/code>方法本质上接受您的配置并为您提供一个基于WebApplication<\/code>构建的WebApplicationBuilder<\/code> ,因此您无法在构建app<\/code>后对其进行修改

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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