Cookie很快死了

时间:2011-10-09 10:54:50

标签: asp.net-mvc-3 cookies

我在服务器上遇到cookie问题。 Cookie很快死了。在localhost cookie上做得很好。但另一方的陌生感。本身cookie存在,但该代码看不到它

对于创建cookie,我使用了这段代码

    public void SignIn(BaseUser user, bool isRememberMe)
    {
        string data = string.Format("{0},{1}, {2}", user.Id, user.Role.RoleName, user.Role.IsSuperRole);
        if (string.IsNullOrEmpty(user.UserName))
        {
            throw new ArgumentException("Error", "userName");
        }

        var ticket = new FormsAuthenticationTicket(
            1,
            user.UserName,
            DateTime.Now.ToLocalTime(),
            DateTime.Now.ToLocalTime().AddDays(30),
            isRememberMe,
            data,
            FormsAuthentication.FormsCookiePath);

        var encryptedTicket = FormsAuthentication.Encrypt(ticket);

        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
            {
                HttpOnly = true,
                Secure = FormsAuthentication.RequireSSL,
                Path = FormsAuthentication.FormsCookiePath,
            };

        if (FormsAuthentication.CookieDomain != null)
        {
            cookie.Domain = FormsAuthentication.CookieDomain;
        }

        HttpContext.Current.Response.Cookies.Add(cookie);
    }

对于读取和更改cookie,我使用此代码

    protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
        HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
        Identity id = null;

        if (authCookie != null)
        {
            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            id = this.GetUserIdentity(authTicket);
            authCookie.Expires = DateTime.Now.AddDays(30);
            HttpContext.Current.Response.Cookies.Add(authCookie);
        }
        else
        {
            id = new Identity();
        }

        var user = new Principal(id, id.RoleName);
        Context.User = user;
    }

    private Identity GetUserIdentity(FormsAuthenticationTicket ticket)
    {
        string[] userDetal = ticket.UserData.Split(Convert.ToChar(","));
        int id = int.Parse(userDetal[0]);
        string roleName = userDetal[1];
        bool isSuperRole;
        bool.TryParse(userDetal[2], out isSuperRole);
        string userName = ticket.Name;

        return new Identity(id, userName, true, isSuperRole, roleName);
    }

0 个答案:

没有答案