Asp.net MVC UserManager Update



我试图更新数据库中的用户数据,我正在从视图中获取值,我将这些数据分配给当前用户。然而,当我更新用户的数据var result = await UserManager.UpdateAsync(userAccount);时,我在该行中出现了一个错误,它被写为一个或多个实体的验证失败。查看'EntityValidationErrors'属性了解更多细节。 .我怎么能解决这个问题?由于

控制器:

public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> ModifyAccount(ModifyUserAccountViewModel model)
    {
        var user = await UserManager.FindByIdAsync(int.Parse(User.Identity.GetUserId()));
        UserAccount userAccount = (UserAccount)user;
        userAccount.surname = model.surname;
        userAccount.name = model.name;
        userAccount.Email = model.email;
        var result = await UserManager.UpdateAsync(userAccount);
        if (result.Succeeded)
        {
            return RedirectToAction("Index", new { Message = "Account modyfyied successfully!" });
        }
        AddErrors(result);
        return View("Error");
     }

Startup.cs:

public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);          
    }

你可以尝试,正如@Praveen Prasad在这篇文章中建议的,捕捉异常,看看你有什么验证错误:

 [HttpPost]
 [ValidateAntiForgeryToken]
 public async Task<ActionResult> ModifyAccount(ModifyUserAccountViewModel model)
 {
    var user = await UserManager.FindByIdAsync(int.Parse(User.Identity.GetUserId()));
    UserAccount userAccount = (UserAccount)user;
    userAccount.surname = model.surname;
    userAccount.name = model.name;
    userAccount.Email = model.email;
    try { 
      var result = await UserManager.UpdateAsync(userAccount);
    }
    catch (DbEntityValidationException dbEx)
    {
        foreach (var validationErrors in dbEx.EntityValidationErrors)
        {
            foreach (var validationError in validationErrors.ValidationErrors)
            {
               Trace.TraceInformation("Property: {0} Error: {1}", 
                                validationError.PropertyName, 
                                validationError.ErrorMessage);
            }
        }
    }
    if (result.Succeeded)
    {
       return RedirectToAction("Index", new { Message = "Account modyfyied successfully!" });
    }
    AddErrors(result);
    return View("Error");
}

相关内容

  • 没有找到相关文章

最新更新