为什么角色显示为“不存在"?即使存在于数据库中(asp.net mvc) [英] Why does a role shows as "not exist" even when present in the database (asp.net mvc)

查看:203
本文介绍了为什么角色显示为“不存在"?即使存在于数据库中(asp.net mvc)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在注册用户时将用户添加到角色中,因此我为角色添加了种子,并使用migrations.cs类中的以下代码更新了数据库

I'm trying to add users to a role when registering a user so i seeded the roles and updated the database with the code below in the migrations.cs class

        var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
        string[] roleNames = { "Admin", "Reviewer", "User" };
        IdentityResult roleResult;
        foreach (var roleName in roleNames)
        {
            if (!RoleManager.RoleExists(roleName))
            {
                roleResult = RoleManager.Create(new IdentityRole(roleName));
            }
        }

我试图将roleNames提取到我的accountcontroller类的下拉列表中

i tried to fetch the roleNames into a dropdownlist in my accountcontroller class

public ActionResult Register()
{
    var model = new RegisterViewModel();
        model.RolesList = new SelectList(_db.Roles, "Id", "Name");

    return View(model);
}

//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser()
        {
            UserName = model.UserName,
            PortalUser = new PortalUser()
            {
                Email = model.Email,
                UserName = model.UserName
            }
        };
        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            UserManager.AddToRole(user.Id, model.Roleid);                
            return RedirectToAction("Index", "ApplicationReview");
        }
        else
        {
            AddErrors(result);
        }
    }
    model.RolesList = new SelectList(_db.Roles, "Id", "Name");
    // If we got this far, something failed, redisplay form
    return View(model);
}

但是调试器此时显示错误

However the debugger showed an error at this point

UserManager.AddToRole(user.Id,model.Roleid); 角色bec759ac-55ca-40f0-a8b8-00de314dd2b3不存在.

UserManager.AddToRole(user.Id, model.Roleid); Role bec759ac-55ca-40f0-a8b8-00de314dd2b3 does not exist.

但是该角色存在于数据库中,所以我对问题所在感到困惑

however this role exist in the database so i'm confused as to what the problem is

推荐答案

第二个参数是字符串角色,如"Reviewer" not 的角色ID.这是错误的,因为Name几乎没有与该GUID相等的角色.

The second parameter is the string role, as in "Reviewer" not the id of the role. It's erroring out because there is literally no role with Name equal to that GUID.

请参阅: https://msdn.microsoft .com/en-us/library/dn497483(v = vs.108).aspx

这篇关于为什么角色显示为“不存在"?即使存在于数据库中(asp.net mvc)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆