MVC5:UserManager.AddToRole():“将用户添加到角色时出错:找不到用户 ID"?

MVC5: UserManager.AddToRole(): quot;Error Adding User to Role: UserId not foundquot;?(MVC5:UserManager.AddToRole():“将用户添加到角色时出错:找不到用户 ID?)
本文介绍了MVC5:UserManager.AddToRole():“将用户添加到角色时出错:找不到用户 ID"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用 MVC5/EF6 并尝试使用 Code-First 迁移的新身份验证.解决方案中的所有内容当前正在构建中,我可以添加 Migration,但是当我通过 VS2013 中的 package manager console 执行 update-database,我的 Configuration.cs 文件无法将我的测试数据完全处理到我的表中并输出 ErrorAdding User to Role: UserId not found.

I have been experimenting with MVC5/EF6 and trying out the new Identity Authentication with Code-First Migrations. Everything in the solution is currently building and I can add a Migration, but when I perform an update-database through the package manager console in VS2013, my Configuration.cs file fails to fully process my test data into my Tables and outputs Error Adding User to Role: UserId not found.

我已尝试显式设置用户 ID 并让它由管理器生成(如在某些示例中所示),但每次我都会收到相同的错误消息.我知道错误在我的 #region User &我的 Configuration.cs 文件的用户角色,但我不确定为什么:

I have tried explicitly setting a User ID and leaving it to be generated by the Manager (as seen in some examples), but each time I receive the same error message. I know the error is failing in my #region User & User Roles of my Configuration.cs file, but I'm not sure why:

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using PersonalPortfolio2.Helper;
using PersonalPortfolio2.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Diagnostics;
using System.Linq;

namespace PersonalPortfolio2.Models
{
    public sealed class Configuration : DbMigrationsConfiguration<PersonalPortfolio2.Models.ApplicationDbContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(PersonalPortfolio2.Models.ApplicationDbContext context)
        {
            BlobHelper bh = new BlobHelper();
            //LocationHelper lh = new LocationHelper();
            ApplicationDbContext db = new ApplicationDbContext();

            #region Roles
            try
            {
                List<string> myRoles = new List<string>(new string[] { "Root", "Admin", "Outsider", "Client", "Primary" });
                var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));

                foreach (string r in myRoles)
                {
                    RoleManager.Create(new IdentityRole(r));
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error Create Roles: " + ex.Message);
            }
            #endregion

            #region User & User Roles
            var store = new UserStore<ApplicationUser>(context);
            var manager = new UserManager<ApplicationUser>(store);

            List<ApplicationUser> myUsers = GetTestUsers();
            var passwordHasher = new PasswordHasher();

            foreach (var u in myUsers)
            {
                var userExists = db.Users.Where(a => a.Email == u.Email).FirstOrDefault();
                if (userExists == null)
                {
                    var user = new ApplicationUser
                    {
                        Email = u.Email,
                        PasswordHash = passwordHasher.HashPassword("P@ssword1"),
                        LockoutEnabled = false,
                        Name = u.Name,
                        Position = u.Position,
                        RegisteredDate = DateTime.Now,
                        LastVisitDate = DateTime.Now,
                        OrganizationId = u.OrganizationId,
                        ProfilePictureSrc = u.ProfilePictureSrc,
                    };

                    try
                    {
                        var userCreateResult = manager.Create(user);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Error Add User: " + ex.Message + "
" + ex.InnerException);
                    }

                    // Add User to Roles
                    List<string> usersRoles = GetUserRoles(u.Email);
                    bool codeHit = false;
                    foreach (string role in usersRoles)
                    {
                        try
                        {
                            codeHit = true;
                            manager.AddToRole(user.Id, role);
                        }
                        catch (Exception ex)
                        {
                            // ERROR!
                            throw new Exception("Error Adding User to Role: " + ex.Message + "
" + ex.Data + "
" + ex.InnerException + "
Name: " + user.Name + "
Email: " + user.Email + "
user.ID: " + user.Id + "
u.Id: " + u.Id + "
Role: " + role + "
CodeHit: " + codeHit);
                        }
                    }
                }

            }
            #endregion

}

            #region Helpers
            private List<ApplicationUser> GetTestUsers()
            {
                List<ApplicationUser> testUsers = new List<ApplicationUser>
                {
                    new ApplicationUser
                    {
                        Id = "1",
                        Email = "Admin@abc.com",
                        Name = "Admin User",
                        RegisteredDate = System.DateTime.Now,
                        LastVisitDate = System.DateTime.Now,
                        Position = "Site Administrator",
                        PhoneNumber = "1234564321",
                    },
                    new ApplicationUser
                    {
                        Id = "2",
                        Email = "first.last@hotmail.com",
                        Name = "James Woods",
                        RegisteredDate = System.DateTime.Now,
                        LastVisitDate = System.DateTime.Now,
                        Position = "Software Developer / Web Designer",
                        PhoneNumber = "1234567890",
                    },
                    new ApplicationUser
                    {
                        Id = "3",
                        Email = "tyler.perry@gmail.com",
                        Name = "Tyler Perry",
                        RegisteredDate = System.DateTime.Now,
                        LastVisitDate = System.DateTime.Now,
                        Position = "Company Contact",
                        PhoneNumber = "1234567890",
                    }
                };
                return testUsers;
            }


            public List<string> GetUserRoles(string user)
            {
                List<string> myRoles = new List<string>();
                switch (user)
                {
                        //"Root", "Admin", "Outsider", "Client", "Primary"
                    case "Admin@abc.com":
                        myRoles = new List<string>(new string[] { "Root", "Admin" });
                        break;
                    case "first.last@hotmail.com":
                        myRoles = new List<string>(new string[] { "Admin" });
                        break;
                    case "tyler.perry@gmail.com":
                        myRoles = new List<string>(new string[] { "Client", "Outsider" });
                        break;
                    default:
                        myRoles = new List<string>(new string[] {"[user] not found."});
                        break;
                }
                return myRoles;
            }
            #endregion

    }
}

谁能在这里提供一些我可能忽略的见解?有关详细信息,我当前的 catch 语句正在输出以下内容:

Can anyone offer some insight here with what I may be overlooking? For full details, my current catch statment is outputting the following:

Error Adding User to Role: UserId not found.
System.Collections.ListDictionaryInternal

Name: Admin User
Email: Admin@abc.com
user.ID: 1
u.Id: 1
Role: Root
CodeHit: True

当我为我的管理员用户注释掉显式 Id = "1", 时,user.IDu.Id 变为:ab753316-3d7b-4f98-a13a-d19f7c926976.我原以为可能是我的 GetTestUsers()GetUserRoles(u.Email) 的辅助方法是问题所在,但在我的 try/catch 和我正在使用的 codeHit 布尔变量,我已经验证问题肯定来自 manager.AddToRole(user.Id, role).

When I comment out the explicit Id = "1", for my Admin User, the user.ID and u.Id becomes: ab753316-3d7b-4f98-a13a-d19f7c926976. I had thought it might be my helper methods of GetTestUsers() or GetUserRoles(u.Email) which were the issue, but between my try/catch and the codeHit boolean variable I am using, I have verified the issue is definitely coming from manager.AddToRole(user.Id, role).

推荐答案

我把这个留给任何可能遇到类似问题的人.我有完全相同的症状".事实证明,与存储的密码相关的问题不符合配置的密码策略(至少一个大写字符、一个小写字符等).

I am leaving this here for anyone that might have had a similar issue. I had exactly the same "symptoms". It turns out that the problem related to the password being stored not adhering to the configured password policy (at least one uppercase char, one lowercase char, etc etc).

根据以下评论和答案,一般来说,当任何用户创建约束或策略未遵循时,都会引发相同的模糊错误消息.

As per below comments and answers, in general, the same vague error message is thrown when any of the user creation constraints or policies are not followed.

这可能包括以下内容:

  • 未遵守密码政策(这似乎是最常见的原因)
  • 必填字段作为空字符串/null 传递
  • 用户名或电子邮件重复

确实有很多问题会导致此错误发生.如果以上方法不能解决你的问题,我建议如下:

There is really a wide range of issues which can cause this error to occur. If the above does not solve your problem, I suggest the following:

  1. 熟悉身份提供者的规则和政策,因为它是为您的解决方案设置的
  2. 根据下面@Ted 的回答,在 UserManager.Create 方法上跟踪或设置断点以查看结果,因为这可能会揭示问题的原因.

这篇关于MVC5:UserManager.AddToRole():“将用户添加到角色时出错:找不到用户 ID"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)