ASP.NET身份更新用户 - Nullreference

时间:2014-08-12 10:01:19

标签: c# asp.net entity-framework webforms asp.net-identity

我试图更新用户并获得空引用。 这是我更新用户的代码,当我在else中设置firstname时,我得到null引用(当对象不存在时,我尝试创建它但它不起作用)

属性工作正常,因为我的注册工作,如果用户配置对象存在,那么它也很好

  var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
        var currentUser = manager.FindById(User.Identity.GetUserId());

        if (currentUser.UserProfileInfo != null)
        {

            currentUser.UserProfileInfo.FirstName = Firstname.Text;
            currentUser.UserProfileInfo.LastName = Lastname.Text;
            currentUser.UserProfileInfo.Adress = Adress.Text;
            currentUser.UserProfileInfo.Zip = Zip.Text;
            currentUser.UserProfileInfo.City = City.Text;
            currentUser.UserProfileInfo.Mobile = Mobile.Text;

            manager.UpdateAsync(currentUser);

        }
        else
        {

            UserProfileInfo UserProfileInfo = new UserProfileInfo();
            currentUser.UserProfileInfo.FirstName = Firstname.Text;
            currentUser.UserProfileInfo.LastName = Lastname.Text;
            currentUser.UserProfileInfo.Adress = Adress.Text;
            currentUser.UserProfileInfo.Zip = Zip.Text;
            currentUser.UserProfileInfo.City = City.Text;
            currentUser.UserProfileInfo.Mobile = Mobile.Text;

            manager.UpdateAsync(currentUser);

        }

由于

1 个答案:

答案 0 :(得分:1)

我想到了两种可能的情景。用这些小信息很难说,但这是我的意见:

  • 尝试使用User.Identity.GetUserId()时未登录。这将返回id的null值,从而导致null currentUser。您没有检查currentUser是否为null,因此当您尝试访问null对象的属性时,会导致null引用异常。

  • 您获取ApplicationUser对象但未创建UserProfileInfo属性。这可能有很多原因,具体取决于您的实施。

您应该在以下行

上设置断点
currentUser.UserProfileInfo.FirstName = Firstname.Text;

检查currentUser是否为null或UserProfileInfo是否为null。

试试这个:

else
{

    currentUser.UserProfileInfo = new UserProfileInfo();
    currentUser.UserProfileInfo.FirstName = Firstname.Text;
    currentUser.UserProfileInfo.LastName = Lastname.Text;
    currentUser.UserProfileInfo.Adress = Adress.Text;
    currentUser.UserProfileInfo.Zip = Zip.Text;
    currentUser.UserProfileInfo.City = City.Text;
    currentUser.UserProfileInfo.Mobile = Mobile.Text;

    manager.UpdateAsync(currentUser);

}