2

我创建了一个实现IUser的自定义User类。当我注册一切正常时,表已创建(如果它们不存在)并且看起来一切正常,但是,正如主题所述,我无法让 User.GetUserId() 工作。它总是返回 null 这真的很烦人。

这是我的用户类:

public class User : IUser
{
    public User()
    {
        this.LastLoginDate = DateTime.UtcNow;
        this.DateCreated = DateTime.UtcNow;
    }

    public User(string userName)
    {
        this.Id = Guid.NewGuid().ToString();
        this.UserName = userName;

        this.CreatedBy = this.Id;

        this.LastLoginDate = DateTime.UtcNow;
        this.DateCreated = DateTime.UtcNow;

        this.IsApproved = true;
    }

    [Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredUserName")]
    public string UserName { get; set; }

    public string Id { get; set; }
    [Required] public string CompanyId { get; set; }

    [Required] public string CreatedBy { get; set; }
    public string ModifiedBy { get; set; }

    public DateTime DateCreated { get; set; }
    public DateTime? DateModified { get; set; }
    public DateTime LastLoginDate { get; set; }

    [Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredTitle")]
    public string Title { get; set; }
    [Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredFirstName")]
    public string Forename { get; set; }
    [Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredLastName")]
    public string Surname { get; set; }

    [Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredEmail")]
    public string Email { get; set; }
    public string JobTitle { get; set; }
    public string Telephone { get; set; }
    public string Mobile { get; set; }
    public string Photo { get; set; }
    public string LinkedIn { get; set; }
    public string Twitter { get; set; }
    public string Facebook { get; set; }
    public string Google { get; set; }
    public string Bio { get; set; }

    public string CompanyName { get; set; }

    [Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredCredentialId")]
    public string CredentialId { get; set; }
    [Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredSecurityCode")]
    public bool IsLockedOut { get; set; }
    public bool IsApproved { get; set; }

    [Display(Name = "Can only edit own assets")]
    public bool CanEditOwn { get; set; }
    [Display(Name = "Can edit assets")]
    public bool CanEdit { get; set; }
    [Display(Name = "Can download assets")]
    public bool CanDownload { get; set; }
    [Display(Name = "Require approval to upload assets")]
    public bool RequiresApproval { get; set; }
    [Display(Name = "Can approve assets")]
    public bool CanApprove { get; set; }
    [Display(Name = "Can synchronise assets")]
    public bool CanSync { get; set; }

    public bool AgreedTerms { get; set; }
    public bool Deleted { get; set; }
}

public class UserContext : IdentityStoreContext
{
    public UserContext(DbContext db)
        : base(db)
    {
        this.Users = new UserStore<User>(this.DbContext);
    }
}

public class UserDbContext : IdentityDbContext<User, UserClaim, UserSecret, UserLogin, Role, UserRole>
{
}

这是我的注册功能:

    //
    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            try
            {
                // Create a profile, password, and link the local login before signing in the user
                var companyId = Guid.NewGuid().ToString();
                var user = new Skipstone.Models.User(model.UserName)
                {
                    CompanyId = companyId,
                    Title = model.Title,
                    Forename = model.Forename,
                    Surname = model.Surname,
                    Email = model.Email,
                    CompanyName = model.CompanyName,
                    CredentialId = model.CredentialId
                };

                if (await IdentityStore.CreateLocalUser(user, model.Password))
                {
                    // Create our company
                    var company = new Company()
                    {
                        Id = companyId,
                        CreatedBy = user.Id,
                        ModifiedBy = user.Id,
                        Name = model.CompanyName
                    };

                    using (var service = new CompanyService())
                    {
                        service.Save(company);
                    }

                    await AuthenticationManager.SignIn(HttpContext, user.Id, isPersistent: false);

                    var test = User.Identity.IsAuthenticated; // returns true
                    var u = User.Identity.GetUserId(); // returns null

                    return RedirectToAction("Setup", new { id = companyId });
                }
                else
                {
                    ModelState.AddModelError("", "Failed to register user name: " + model.UserName);
                }
            }
            catch (IdentityException e)
            {
                ModelState.AddModelError("", e.Message);
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

var test 返回 true,因此它知道用户现在已登录。 var u 为空,因此 User.Identity.GetUserId() 无法正常工作。

有谁知道为什么?

我可以根据要求发布更多代码:)

更新 1

通过创建一个新项目并使用默认值进行测试,我发现在Register方法中调用的 User.Identity返回 null。

但是在新项目中,在其他任何地方调用它都会返回正确的信息,但在我的项目中,我得到的所有内容都为 null。

更新 2

它肯定与自定义User类有关。我在我的新项目上创建了一个,同样的事情发生了。所以,出了点问题:) 现在我只需要弄清楚是什么!?!

4

1 回答 1

0

我假设在您的项目中某处有一行数据库连接初始化,如下所示:

WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true)

因此,请确保在此行中使用“Id”而不是“UserId”

于 2013-11-14T17:11:28.603 回答