MiniProfiler ASP.NET Core - 基于用户角色的 ShouldProfile

MiniProfiler ASP.NET Core - ShouldProfile based on user role

我在 ASP.NET 核心应用程序中设置了 MiniProfiler。分析工作正常。

但是,我只希望管理员能够配置文件。

我在 ConfigureServices 中有以下内容:

services.AddMiniProfiler(options =>
{
    options.ShouldProfile = request =>
        request.HttpContext.User.IsInRole("Admin");
});

问题是,该方法中似乎没有加载用户身份。
User.Identity.Name 属性 为空,没有声明。
我的猜测是这个调用发生在该信息被填充之前?

如何根据用户身份进行分析?

您需要知道,根据 the docsClaimsPrincipal.IsInRole() 方法检查类型为 ClaimsIdentity.RoleClaimType 的声明。确保您已添加角色声明。

这是一个您可以关注的工作演示:

1.Register 名为 a@qq.com 的用户成功。

2.Generate 角色并向用户添加具有声明的角色:

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.Startup.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();
    });
}

结果: