从.NET6中的构建器设置中访问当前环境(开发、生产等)



我正在.NET 6中构建一个使用身份验证和基于策略的授权的应用程序。两者功能良好。但是,我需要创建一种在开发环境中绕过授权的方法。下面是我在程序中的代码。cs.

我已经创建了一个禁用授权的类,并将其添加到生成器CCD_;发展"我的问题是,我不知道如何从构建器中的获取当前环境(我知道如何在构建完成后完成,例如app.Environment.IsDevelopment()(。

我在网上搜索过,但我能找到的所有解决方案都涉及到对Startup((和ConfigureServices((方法的注入,这两种方法都已被.NET 6中的WebApplication.CreateBuilder所取代。

在构建应用程序之前,获得环境的最有效方法是什么?

当前代码(Program.cs(

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddControllersWithViews();
builder.Services.AddServerSideBlazor();
builder.Services.AddHttpClient();
builder.Services.AddSingleton<IAppState, AppState>();
builder.Services.AddScoped<IAuthorizationHandler, IsAdminHandler>();
...

//Add authentication and register CAS as the authentication handler
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
// Add cookie authentication
...
builder.Services.AddAuthorization(options =>
{
// Add access policies
options.AddPolicy("IsAdmin", Policies.IsAdminPolicy());
options.AddPolicy("IsManager", Policies.IsManagerPolicy());
options.AddPolicy("IsUser", Policies.IsUserPolicy());
options.AddPolicy("IsReadOnly", Policies.IsReadOnlyPolicy());
// Add fallback authorization which blocks unauthenticated access to all pages
// unless the [AllowAnonymous] attribute is applied to the route in the controller
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
}
);
// Disable authorization in DEV
builder.Services.AddSingleton<IAuthorizationHandler, DisableAuthorization>();
// Run the builder and return the configured application to "app" 
var app = builder.Build();

// Configure the HTTP request pipeline by adding middleware
if (app.Environment.IsDevelopment())
{
// Use detailed exception page (for development environment only)
app.UseDeveloperExceptionPage();
// Require HTTPS connection.  The default HSTS value is 30 days. 
app.UseHsts();
}
else if (app.Environment.IsProduction())
{
// Enable standard error page
app.UseExceptionHandler("/Error");
// Require HTTPS connection. The default HSTS value is 30 days. 
// You may want to change this for production scenarios, 
// see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
else
{
throw new GenericException("Environment has not been set or is incorrect");
}

您可以在WebApplicationBuilder:上使用Environment属性

var isDev = builder.Environment.IsDevelopment();

最新更新