2

に保存されているロールのリストを取得するには、次の方法がありますAspNetRoles

    [AllowAnonymous]
    public async Task<ActionResult> Register()
    {
        //Get the list of Roles
        ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Name", "Name");

        return View();
    }

次に、次のように表示します

    <div class="form-group">
        <label class="col-md-2 control-label">
            Select User Role
        </label>
        <div class="col-md-10">
            @foreach (var item in (SelectList)ViewBag.RoleId)
            {
                <input type="checkbox" name="SelectedRoles" value="@item.Value" class="checkbox-inline" />
                @Html.Label(item.Value, new { @class = "control-label" })
            }
        </div>
    </div>

しかし、ページをロードするとObject reference not set to an instance of an object.エラーが発生します

175 行目: ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Name", "Name");

これはRoleManager定義です

    public ApplicationRoleManager RoleManager
    {
        get
        {
            return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
        }
        private set
        {
            _roleManager = value;
        }
    }

これはApplicationRoleManagerモデルです

// Configure the RoleManager used in the application. RoleManager is defined in the ASP.NET Identity core assembly
public class ApplicationRoleManager : RoleManager<ApplicationRole>
{
    public ApplicationRoleManager(IRoleStore<ApplicationRole, string> roleStore)
        : base(roleStore)
    {
    }

    public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
    {
        return new ApplicationRoleManager(new ApplicationRoleStore(context.Get<ApplicationDbContext>()));
    }
}
4

2 に答える 2

4

Startup.Auth で、RoleManager を次のように参照します。

    public void ConfigureAuth(IAppBuilder app)
    {
        // Add this reference
        app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
    }

コントローラーに次のコンストラクターが含まれていることを確認してください。

        // Include this
        private ApplicationRoleManager _roleManager;
        // You already have this
        public ApplicationRoleManager RoleManager { get { return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>(); } private set { _roleManager = value; } }

再構築して、もう一度やり直してください。これで問題が解決することを願っています。

于 2016-03-07T09:02:23.760 に答える
2

RoleManager.Rolesあなたの財産を確認してください。DBから何も返さないようです。UserRolesまた、テーブルに少なくとも 1 つの役割エンティティがあることを確認してください

于 2016-03-07T07:36:15.723 に答える