【问题标题】:How to return all records in AspNetUserClaims如何返回 AspNetUserClaims 中的所有记录
【发布时间】:2020-08-25 12:58:36
【问题描述】:

在使用 Identity and Entity Framework 的 ASP.NET Core / Razor Pages 中,我可以查看 AspNetUsers 表中的所有记录,如下所示:

public class ViewAspNetDataModel : PageModel
{
    private readonly UserManager<ApplicationUser> userManager;

    public ViewAspNetDataModel(UserManager<ApplicationUser> userManager)
    {
        this.userManager = userManager;
    }

    public IQueryable<ApplicationUser> SiteUsers { get; set; }

    public void OnGet()
    {
        SiteUsers = userManager.Users; // Can now use @foreach (var user in Model.SiteUsers) {} in the cshtml page.
    }
}

我还需要能够查看 AspNetUserClaims 表中的所有记录,但不知道如何执行此操作。我可以包括

IUserClaimStore<ApplicationUser> userClaims

在构造函数中,但不确定如何在 Startup.cs 中解决此问题,并且 userClaims 也没有包含数据库表中所有声明的属性。获取这些数据的最佳方式是什么?感谢您提供任何信息。

【问题讨论】:

    标签: c# asp.net-core asp.net-identity razor-pages


    【解决方案1】:

    我现在可以回答我自己的问题,以防这对其他人有用:ApplicationDbContext 有一个 UserClaims 属性,该属性包含 AspNetUserClaims 表中的所有声明。按如下方式填充模型属性:

    public class ViewAspNetDataModel : PageModel
    {
        private readonly ApplicationDbContext context;
    
        public ViewAspNetDataModel(ApplicationDbContext context)
        {
            this.context = context;
        }
    
        public IQueryable<IdentityUserClaim<int>> UserClaims { get; set; }
    
        public void OnGet()
        {
            UserClaims = context.UserClaims;
        }
    }
    

    然后在 cshtml 文件中你可以使用类似的东西:

    <table class="table table-striped">
        <thead>
            <tr style="font-size:small; color:yellow; background-color:#A00000">
                <th class="align-middle p-1" style="font-weight:normal">ID</th>
                <th class="align-middle p-1" style="font-weight:normal">User ID</th>
                <th class="align-middle p-1" style="font-weight:normal">Claim type</th>
                <th class="align-middle p-1" style="font-weight:normal">Claim value</th>
            </tr>
        </thead>
    
        <tbody>
            @foreach (var claim in Model.UserClaims)
            {
                <tr style="font-size:small">
                    <td class="align-top p-1">@claim.Id</td>
                    <td class="align-top p-1">@claim.UserId</td>
                    <td class="align-top p-1">@claim.ClaimType</td>
                    <td class="align-top p-1">@claim.ClaimValue</td>
                </tr>
            }
        </tbody>
    </table>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      相关资源
      最近更新 更多