通过ASP.NET身份2

时间:2016-09-17 09:13:54

标签: c# asp.net-mvc asp.net-identity automapper asp.net-identity-2

我在ASP.NET Identity 2项目中使用MVC 5,我希望使用Student方法更新UserManager.Update()数据。但是,当我从ApplicationUser类继承时,我需要在调用update方法之前将Student映射到ApplicationUser。另一方面,当使用我也用于创建新Student的方法时,由于并发性而导致错误,因为我创建了一个新实例而不是更新。由于我无法使用AutoMapper来解决问题,我需要一个稳定的修复来解决问题而不使用AutoMapper。能否请您澄清如何解决这个问题?我将StudentViewModel传递给Controller中的Update方法,然后我需要将其映射到Student,然后将其作为UserManager.Update()传递给ApplicationUser方法。另一方面,我想知道我是否应该在Controller阶段检索并发送密码,而不是为安全问题转到View?你能否告诉我这个问题(在用户更新期间我不更新密码,我必须在数据库中保留用户的密码)。任何帮助将不胜感激。

实体类:

public class ApplicationUser : IdentityUser<int, ApplicationUserLogin,
                                     ApplicationUserRole, ApplicationUserClaim>, IUser<int>
{
    public string Name { get; set; }
    public string Surname { get; set; } 
    //code omitted for brevity
}

public class Student: ApplicationUser
{     
    public int? Number { get; set; }
}


控制器:

[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Update([Bind(Exclude = null)] StudentViewModel model)
{
    if (ModelState.IsValid)
    {
        ApplicationUser user = UserManager.FindById(model.Id);

        user = new Student
        {
            Name = model.Name,
            Surname = model.Surname,
            UserName = model.UserName,
            Email = model.Email,
            PhoneNumber = model.PhoneNumber,
            Number = model.Number, //custom property
            PasswordHash = checkUser.PasswordHash
        };

        UserManager.Update(user);
    }
}

3 个答案:

答案 0 :(得分:33)

无需将.__getattribute__作为student传递给ApplicationUser方法(因为UserManager.Update()类继承(因此){ {1}})。

您的代码存在的问题是您正在使用Student运算符,从而创建新学生而不是更新现有学生。

更改代码如下:

ApplicationUser

答案 1 :(得分:1)

我对.netcore 1的回答

这项工作对我来说,我希望可以帮助他们

.c_observation__indicator--country .c_observation__icon {
  background: #000;
  border-radius: 50%;
  width:25px;
  height:25px;
  padding:1px;
}

答案 2 :(得分:0)

这花了我一些时间来理解,但是您只需要使用UserManager。我的任务是简单地使用新的Date更新LoginViewModel。我尝试了不同的方法,但似乎唯一起作用的是FindByEmailAsync,它专用于我的MODEL,因为我没有使用ID登录。

Case SignInStatus.Success
            Dim user As ApplicationUser = Await UserManager.FindByEmailAsync(model.Email)
            user.LastActivityDate = model.LastActivityDate

            UserManager.Update(user)

            Return RedirectToLocal(returnUrl)