62,046
社区成员
发帖
与我相关
我的任务
分享
string data = string.Empty;
//用户数据转成一个字符串。
if (model != null)
data = (new System.Web.Script.Serialization.JavaScriptSerializer()).Serialize(model);
//创建FormsAuthenticationTicket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, model.UserAccount, DateTime.Now, DateTime.Now.AddDays(7), true, data);
//加密
string cookieValue = FormsAuthentication.Encrypt(ticket);
//创建FormsAuthenticationTicket
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue);
cookie.HttpOnly = true;
cookie.Secure = FormsAuthentication.RequireSSL;
cookie.Domain = FormsAuthentication.CookieDomain;
cookie.Path = FormsAuthentication.FormsCookiePath;
cookie.Expires = DateTime.Now.AddDays(7);
System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
//身份验证
FormsAuthentication.RedirectFromLoginPage(model.UserAccount, false);
public void SignIn(HttpContextBase httpContext, string userName, string userId, bool createPersistentCookie)
{
if (String.IsNullOrEmpty(userName))
{
throw new ArgumentException("值不能为 null 或为空。", "userName");
}
if (String.IsNullOrEmpty(userId))
{
throw new ArgumentException("值不能为 null 或为空。", "roles");
}
var ticket = new FormsAuthenticationTicket(
1,
userName,
DateTime.Now,
DateTime.Now.Add(FormsAuthentication.Timeout),
createPersistentCookie,
userId);
SetAuthCookie(httpContext, ticket);
}
public void SignOut()
{
FormsAuthentication.SignOut();
}
public void SetAuthCookie(HttpContextBase httpContext, FormsAuthenticationTicket authenticationTicket)
{
//DateTime issueDate = DateTime.Now;
//string protectedTicket = FormsAuthentication.Encrypt(authenticationTicket);
//HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, protectedTicket);
//cookie.HttpOnly = true;
//cookie.Expires = issueDate.AddMinutes(20);
//HttpContext.Current.Response.Cookies.Add(cookie);
var encryptedTicket = FormsAuthentication.Encrypt(authenticationTicket);
httpContext.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) { Expires = CalculateCookieExpirationDate() });
}