我正在尝试使用 Azure Active Directory B2C 启用对我自己的 Web api 的身份验证,并按照官方文档提供的步骤进行操作,我需要在我的 startup.cs
中使用此代码,但它是针对 .Net 5 的,我真的不知道如何将其迁移到 .Net 6。你能帮助我吗?
public void ConfigureServices(IServiceCollection services)
{
// Adds Microsoft Identity platform (Azure AD B2C) support to protect this Api
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(options =>
{
Configuration.Bind("AzureAdB2C", options);
options.TokenValidationParameters.NameClaimType = "name";
},
options => { Configuration.Bind("AzureAdB2C", options); });
// End of the Microsoft Identity platform block
services.AddControllers();
}
我的Program.cs
:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Login}/{id?}");
app.Run();
最佳答案
您看到的差异是由于 "top-level statements" feature ,而不一定是 .NET5 与 .NET6。
要添加所需的代码,您可以依赖 builder
对象,它为您提供对服务和配置的访问。
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
// Adds Microsoft Identity platform (Azure AD B2C) support to protect this Api
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(options =>
{
builder.Configuration.Bind("AzureAdB2C", options);
options.TokenValidationParameters.NameClaimType = "name";
},
options => { Configuration.Bind("AzureAdB2C", options); });
// End of the Microsoft Identity platform block
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Login}/{id?}");
app.Run();
关于c# - 如何将ConfigureServices(IServiceCollection 服务)从.Net 5 迁移到.Net 6?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73207427/