Asp.net MVC 5,Identity 2.0无法向用户添加角色

时间:2014-12-03 14:56:06

标签: asp.net asp.net-mvc-5 asp.net-identity-2

我正在尝试使用控制器向特定用户添加角色。但是,我收到了错误

这是我的角色控制器:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RoleAddToUser(string UserName, string RoleName)
{
    ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
    var account = new AccountController();
    account.UserManager.AddToRole(user.Id, RoleName);

    ViewBag.ResultMessage = "Role created successfully !";

    // prepopulat roles for the view dropdown
    var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
    ViewBag.Roles = list;

    return View("ManageUserRoles");
}    

这是我的动作控制器:

public class AccountController : Controller
{
    private ApplicationUserManager _userManager;

    public AccountController()
    {
    }

    public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager )
    {
        UserManager = userManager;
        SignInManager = signInManager;
    }

    public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }

这是我得到的错误:

应用程序中的服务器错误。

对象引用未设置为对象的实例。

描述:执行当前Web请求期间发生了未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

异常详细信息:System.NullReferenceException:未将对象引用设置为对象的实例。

来源错误:

Line 32:             get
Line 33:             {
Line 34:                 return _userManager ??      HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
Line 35:             }
Line 36:             private set

3 个答案:

答案 0 :(得分:0)

错误,&#34;对象引用未设置为对象的实例。&#34;,表示您有一些变量,您正在调用属性或方法,该属性或方法正在评估为null运行时。

例如,您将用户拉出数据库,然后再引用其Id属性,即user.Id。但是,如果找不到用户,则user变量实际上是 null ,而null没有属性Id,因此错误。

每当你有一个可以是一个类型的实例或null的变量时,你需要在使用之前检查一个空值,以确保你不会得到像这样的运行时错误。

if (user != null)
{
    // use your `user` variable here
}

现在,我不确定您的user变量是否实际为空。它可能是其他东西,但这是在调试这样的错误时应该寻找的东西。在Visual Studio中运行调试器并检查操作中的所有变量。如果有空,那么这很可能是你的候选人。

另外,对于世界上所有善良和圣洁的爱,请在另一个控制器中的动作中实例化一个控制器,尤其是为了获得UserManager in默认情况下为AccountController。将相同的属性添加到需要它的每个控制器,如AccountController那样,或者甚至更好,通过DI(依赖注入)容器将其注入控制器并将其设置为请求范围。

答案 1 :(得分:0)

试试这个,

添加Rolemanger类属性并添加AccountController

 public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager, ApplicationRoleManager roleManager)
 {
        UserManager = userManager;
        SignInManager = signInManager;
       RoleManager =roleManager;
 }

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

在您的页面中添加此内容后。用户将此角色分配给用户。将您要分配给用户的角色userIdrolename传递给用户。

var result = UserManager.AddToRole(userId, "RoleName");

答案 2 :(得分:0)

在App_Start文件夹

中的Startup.Auth.cs文件中添加它
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

如下所示:

public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        ...
        ...
    }