簡體   English   中英

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屬性為 null,並且沒有聲明。
我的猜測是這個調用發生在該信息被填充之前?

我如何根據用戶身份進行分析?

您需要知道,根據文檔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();
    });
}

結果:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM