我的 Razor Pages 应用程序配置如下。Startup.cs 包含:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdminRole", policy =>
policy.RequireAuthenticatedUser().RequireRole("Admin"));
});
services.AddMvc()
.AddRazorPagesOptions(options =>
{
options.Conventions.AuthorizePage("/About", "RequireAdminRole");
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc();
}
我有一个具有“管理员”角色的用户。当用户登录并访问“关于”页面时,我得到以下信息:
拒绝访问
您无权访问此资源。
我究竟做错了什么?
更新
如果我在页面方法中删除AuthorizePage
and 使用,然后在页面中输出属性,则显示管理员用户。所以,不知道为什么不工作。GetUsersInRoleAsync("Admin")
About.cshtml.cs
OnGet
UserName
About.cshtml
AuthorizePage
2017 年 5 月 29 日更新
我的源代码在这个Github Resository