将用户添加到角色验证错误中

本文关键字:验证 错误 角色 用户 添加 | 更新日期: 2023-09-27 18:02:58

我在MVC 5中添加用户到角色时遇到了问题。当我运行代码块时,我得到"一个或多个实体的验证失败"。"

"

当我检查实体验证错误时,它们不是很有帮助。

{System.Data.Entity.Validation。DbEntityValidationResult}是我得到的。

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult RoleAddToUser(string UserName, string RoleName)
    {
        using (var context = new ApplicationDbContext())
        {
            //Gets the user details
            ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
            //Add the user to a role, using id ...
            this.UserManager.AddToRole(user.Id, RoleName);
            ViewBag.ResultMessage = "Role created successfully !";
            // prepopulate 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");
        }      
    } 

这是UserManager:

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

我在这一点上真的很沮丧,因为这是我第一次在MVC中使用角色,到目前为止,它还不是一个很好的经验。

我希望这里有人能帮我找到解决这个问题的方法。

注:我使用的代码是基于本教程:在ASP中使用角色。. NET Identity for MVC

这是视图:

@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<p>
    Username : @Html.TextBox("UserName")
    Role Name: @Html.DropDownList("RoleName", (IEnumerable<SelectListItem>)ViewBag.Roles, "Select ...")
</p>
<input type="submit" value="Save" />

这是默认的用户类,添加了一个属性:

public class ApplicationUser : IdentityUser
{
    [Required]
    [MaxLength(13)]
    [MinLength(13)]
    [Key]
    public string IDNumber { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }
}

EDIT:I Found the problem…因为EF使用名称后面跟着ID作为默认键,所以我的应用程序总是混淆UserID(它是一个ID号)和ID字段。谢谢你的帮助。

将用户添加到角色验证错误中

为什么不捕获异常DbEntityValidationResult并检查验证错误?

您可以检查哪个属性是错误的以及为什么。如果任何数据不满足模型属性规则(例如所需的约束),您可能会得到此错误。

尝试添加以下语句…

catch (DbEntityValidationException ex)
{
    foreach (var errors in ex.EntityValidationErrors)
    {
        foreach (var error in errors.ValidationErrors)
        {
            Trace.TraceInformation("Property: {0} Error: {1}", error.PropertyName, error.ErrorMessage);
        }
    }
}