【发布时间】:2019-09-11 18:30:34
【问题描述】:
我正在设置一个新的 Razor Pages 应用程序,并且我想添加基于角色的授权。网络上有很多教程如何使用 ASP.NET MVC 应用程序而不是 Razor 页面。我尝试了一些解决方案,但对我没有任何效果。目前我有一个问题,如何使用角色播种数据库并将此角色添加到每个新注册用户。
这就是我的Startup.cs 的样子:
public async Task ConfigureServices(IServiceCollection services)
{
var serviceProvider = services.BuildServiceProvider();
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>(config =>
{
config.SignIn.RequireConfirmedEmail = true;
})
.AddRoles<IdentityRole>()
.AddDefaultUI(UIFramework.Bootstrap4)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddAuthorization(config =>
{
config.AddPolicy("RequireAdministratorRole",
policy => policy.RequireRole("Administrator"));
});
services.AddTransient<IEmailSender, EmailSender>();
services.Configure<AuthMessageSenderOptions>(Configuration);
services.AddRazorPages()
.AddNewtonsoftJson()
.AddRazorPagesOptions(options => {
options.Conventions.AuthorizePage("/Privacy", "Administrator");
});
await CreateRolesAsync(serviceProvider);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/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.UseCookiePolicy();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
/// <summary>
/// Method that creates roles
/// </summary>
/// <param name="serviceProvider"></param>
/// <returns></returns>
private async Task CreateRolesAsync(IServiceProvider serviceProvider)
{
//adding custom roles
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
string[] roleNames = { "Admin", "Member", "Outcast" };
IdentityResult roleResult;
foreach (var roleName in roleNames)
{
//creating the roles and seeding them to the database
var roleExist = await RoleManager.RoleExistsAsync(roleName);
if (!roleExist)
{
roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
}
}
}
现在这段代码抛出了异常:
System.InvalidOperationException: '无法找到所需的服务。请通过在应用程序启动代码中对“ConfigureServices(...)”的调用中调用“IServiceCollection.AddAuthorizationPolicyEvaluator”来添加所有必需的服务。
添加 AddAuthorizationPolicyEvaluator 没有任何改变。
有什么建议吗?
【问题讨论】:
标签: c# asp.net-mvc identity roles razor-pages