mvc4向会话添加特定数据

时间:2013-10-29 17:50:38

标签: asp.net-mvc asp.net-mvc-4 login session-variables

我有登录表格。当用户登录时,他必须在两种类型之间进行选择并发送用户名和密码。

我可以这样做,我可以连接到我的模型以验证用户身份。然后,如果他输入了正确的名称和密码,我会这样做:

FormsAuthentication.SetAuthCookie(login.UserName, login.RememberMe);

但我需要一种方法来保存他的类型。我想我必须在会议中这样做,我是对的吗?如果是的话,请问怎么样?如果没有,最好的方法是什么?

4 个答案:

答案 0 :(得分:1)

您只需使用控制器中的Session对象:

Session["usertype"] = yourType;

但是我会使用自定义类来存储此类信息,如果您拥有大量用户(重新考虑会话存储位置或在线用户数据位置),您还应该重新设计此解决方案。

答案 1 :(得分:1)

如果您想使用会话,可以使用Session

您可以存储任何内容。因此,如果您愿意,可以存储整个登录对象。

Session["user"] = yourUser;

会话是个好地方,因为它对每个用户都是唯一的。

如果您在Web应用程序中使用MemberShip类,则可以添加自定义字段,我认为这是您问题的最佳解决方案。请参阅此example或此blog post。这不仅会将您的信息保存到用户的会话中,而且还会在数据库中添加此用户类型。

答案 2 :(得分:1)

这取决于。用户关闭浏览器后是否需要保存“类型”?因为如果你将它保存在会话中,下次打开它时它就会消失。

如果确实需要保存,最好使用cookie。

要添加Cookie,您可以执行以下操作:

this.Response.Cookies.Add(new HttpCookie("my-cookie-name", myValueToSave));

答案 3 :(得分:0)

“保存他的类型”是什么意思?你的意思是他的角色?那么用户在应用程序中的角色基本上是什么?如果它是角色那么可能将它存储在Authcookie是正确的地方。您可以在身份验证cookie中添加其他值,甚至可以滚动自己的授权属性,该属性会考虑其他值,然后这些值将在User Principal对象上提供 `public interface ICustomPrincipal:IPrincipal     {       Guid UserID {get;组; }       string FirstName {get;组; }       string LastName {get;组; }       字符串EmailAddress {get;组; }       Guid CompanyID {get;组; }     }

public class CustomPrincipal : ICustomPrincipal
{
    public IIdentity Identity { get; private set; }
    public bool IsInRole(string role)
    {
        return false;
    }

    public CustomPrincipal()
    {

    }

    public CustomPrincipal(IIdentity indentity)
    {
        this.Identity = new GenericIdentity(indentity.Name);
    }
    public CustomPrincipal(string email)
    {
        this.Identity = new GenericIdentity(email);
    }
   public Guid UserID { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public string EmailAddress { get; set; }
   public Guid CompanyID { get; set; }
   public string CompanyName { get; set; }
   public string JobTitle { get; set; }


}`.


 public sealed class CustomAuthoriseAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        bool isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized) return false;

        CustomPrincipal customPrincipal = null;
        HttpCookie authCookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];

        if (authCookie != null)
        {
            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            var serializer = new JavaScriptSerializer();

            if (authTicket != null)
            {
                var serializeModel = serializer.Deserialize<CustomPrincipalSerializeModel>(authTicket.UserData);

                customPrincipal = new CustomPrincipal(authTicket.Name)
                {
                    UserID = serializeModel.UserID,
                    FirstName = serializeModel.FirstName,
                    LastName = serializeModel.LastName,
                    CompanyID = serializeModel.CompanyID,
                    EmailAddress = serializeModel.EmailAddress,
                    CompanyName = serializeModel.CompanyName,
                    JobTitle = serializeModel.JobTitle,

                };
            }
        }


                 HttpContext.Current.User = customPrincipal;

        return isAuthorized;
    }
}

public  class CustomPrincipalSerializeModel
{
  public Guid UserID { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public string EmailAddress { get; set; }
  public Guid CompanyID { get; set; }
  public string CompanyName { get; set; }
  public string JobTitle { get; set; }

}

然后你登录方法可能看起来像这样

 if (!membershipService.IsAccountLockedOut(loginModel.Email) &&
            membershipService.Login(loginModel.Email, loginModel.Password))
        {
            UserDto user = membershipService.GetUserDetail(loginModel.Email);
            var cookieContext = new CookieContext();
            cookieContext.SetAuthenticationToken(user);
            //Need to check if user has reset thier password and needs to change it
            if (!user.PasswordReset)
            {
                return RedirectToLocal(returnUrl);
            }
            else
            {
                return RedirectToAction("ChangePassword", "Account");
            }
        }

Set Authentication Method看起来像这样

public void SetAuthenticationToken(UserDto userDto)
    {
        string userData;
        string encTicket;

        var serializeModel = new CustomPrincipalSerializeModel();
        serializeModel.UserID = userDto.ID;
        serializeModel.FirstName = userDto.FirstName;
        serializeModel.LastName = userDto.LastName;
        serializeModel.EmailAddress = userDto.Email;
        serializeModel.CompanyID = userDto.CompanyID;
        serializeModel.CompanyName = userDto.Company;
        serializeModel.JobTitle = userDto.JobTitle;

        var serializer = new JavaScriptSerializer();
        userData = serializer.Serialize(serializeModel);

        var autTicket = new FormsAuthenticationTicket(1, userDto.Email, DateTime.Now,
                                                      DateTime.Now.AddMinutes(15), false, userData);
        encTicket = FormsAuthentication.Encrypt(autTicket);
        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
        cookie.HttpOnly = true;
        HttpContext.Current.Response.Cookies.Add(cookie);
    }

您需要在整个应用程序中随用户一起旅行的所有数据都可以在身份验证Cookie中找到,并且只要您使用CustomAuthorise属性,就可以在User对象上使用

 [CustomAuthorise]
    [OutputCache(NoStore = true, VaryByParam = "*", Duration = 0)]
    public ActionResult Index()
    {

        var model = _someService.SomeFunction(User.CompanyID);  //Company ID is from Auth Cookie
        return View(model);
    }