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

标签 c# asp.net-core mvc-mini-profiler miniprofiler

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

但是,我只希望管理员能够进行分析。

我在 ConfigureServices 中有以下内容:

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

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

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

最佳答案

你需要知道根据the docs 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.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();
    });
}

结果:

enter image description here

关于c# - MiniProfiler ASP.NET Core - 基于用户角色的 ShouldProfile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64522789/

相关文章:

c# - 从复选框列表中的顶部项目中从 SQL 数据库中选择的数据被复制到所有 Gridview 行

c# - 如何使用 EPPLus 修改图表系列?

c# - 如何从 ASP.NET Core 中的 IMemoryCache 中删除(重置)所有对象

c# - MySql.Data.MySqlClient.MySqlException : Duplicate entry

asp.net-mvc - MiniProfiler MVC DBContext - 无法确定提供者名称

asp.net-mvc - Mvc Mini Profiler 对带有和不带有 RouteBasePath 的文件的请求

c# - 将具有多个参数的 F# 函数转换为 Func 类型 - MathNet.Numerics

c# - 在 Windows CE C# 应用程序上添加相机处理

html - 如何在 Blazor 中更改 CSS 或 "body"元素的类

c# - Stack Exchange MiniProfiler 不显示配置文件框?