在MVC4 FormsAuthentication中使用UserName传递UserId

时间:2014-11-27 09:55:49

标签: asp.net-mvc asp.net-mvc-4 formsauthentication

因为我们在FormsAuthentication中没有UserId所以我想传递它。这是我的代码

public bool IsValid(string email, string password)
    {
        bool IsValid = false;
        var user = db.Users.FirstOrDefault(u => u.Email == email);

        if (user != null)
        {

            if (user.Password == EncryptPassword(password))
            {
                IsValid = true;

            }

        }
        return IsValid;
    }
      if (user.IsValid(user.Email, user.Password))
            {

                FormsAuthentication.SetAuthCookie(user.Email + "|" + user.Id, true);
                return RedirectToAction("Index", "TestValidUser");
            }

现在问题是user.Id

FormsAuthentication.SetAuthCookie()始终为0

我如何设置它?

1 个答案:

答案 0 :(得分:1)

int userId=0;


public bool IsValid(string email, string password,out int userId)
    {

    if (user.Password == EncryptPassword(password))
            {
                IsValid = true;

               userId= user.Id
            }
}

if (user.IsValid(user.Email, user.Password,userId))
            {

                FormsAuthentication.SetAuthCookie(user.Email + "|" + userId, true);
                return RedirectToAction("Index", "TestValidUser");
            }