您需要知道,根据文档,该ClaimsPrincipal.IsInRole()
方法检查类型ClaimsIdentity.RoleClaimType
的声明。确保您已添加角色声明。
这是您可以遵循的工作演示:
1.成功注册用户名a@qq.com
。
2.生成角色并将带有声明的角色添加给用户:
public async Task CreateRolesandUsers()
{
bool x = await _roleManager.RoleExistsAsync("Admin");
if (!x)
{
// first we create Admin role
var role = new IdentityRole();
role.Name = "Admin";
await _roleManager.CreateAsync(role);
//must add the claim,otherwise IsInRole would always be false..
_roleManager.AddClaimAsync(role, new Claim(ClaimTypes.AuthorizationDecision, "Admin")).Wait();
}
var user = _userManager.FindByNameAsync(User.Identity.Name).Result;
if (user != null)
{
var result1 = await _userManager.AddToRoleAsync(user, "Admin");
}
}
2.启动.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultUI();
services.AddMiniProfiler(options =>
{
options.RouteBasePath = "/profiler";
options.ShouldProfile = request =>
request.HttpContext.User.IsInRole("Admin");
options.SqlFormatter = new StackExchange.Profiling.SqlFormatters.InlineFormatter();
});
services.AddControllersWithViews();
services.AddRazorPages();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication(); //be sure add this
app.UseAuthorization();
app.UseMiniProfiler(); //add this before UseEndpoints
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
结果: