在 ASP.NET 中使用永久用户登录会话 此示例描述了如何在 ASP.NET 中创建永久用户登录会话。示例代码包含一个 ASP.NET MVC4 项目,用于控制用户注册和登录过程。但是您可以在任何类型的 ASP.NET 项目中使用这种技术。但简单来说,您可以使用此代码
该类的功能是向浏览器 cookie 集合添加一个表单身份验证票证,并具有有效期。
public sealed class CookieHelper
{
private HttpRequestBase _request;
private HttpResponseBase _response;
public CookieHelper(HttpRequestBase request,
HttpResponseBase response)
{
_request = request;
_response = response;
}
//[DebuggerStepThrough()]
public void SetLoginCookie(string userName,string password,bool isPermanentCookie)
{
if (_response != null)
{
if (isPermanentCookie)
{
FormsAuthenticationTicket userAuthTicket =
new FormsAuthenticationTicket(1, userName, DateTime.Now,
DateTime.MaxValue, true, password, FormsAuthentication.FormsCookiePath);
string encUserAuthTicket = FormsAuthentication.Encrypt(userAuthTicket);
HttpCookie userAuthCookie = new HttpCookie
(FormsAuthentication.FormsCookieName, encUserAuthTicket);
if (userAuthTicket.IsPersistent) userAuthCookie.Expires =
userAuthTicket.Expiration;
userAuthCookie.Path = FormsAuthentication.FormsCookiePath;
_response.Cookies.Add(userAuthCookie);
}
else
{
FormsAuthentication.SetAuthCookie(userName, isPermanentCookie);
}
}
}
}
该功能用于登录页面或登录按钮点击控制。在随附的示例项目中,以下函数是在 AccountController 类中编写的。该函数验证用户的登录,然后向浏览器添加一个永久的表单身份验证票。
private bool Login(string userName, string password,bool rememberMe)
{
if (Membership.ValidateUser(userName, password))
{
CookieHelper newCookieHelper =
new CookieHelper(HttpContext.Request,HttpContext.Response);
newCookieHelper.SetLoginCookie(userName, password, rememberMe);
return true;
}
else
{
return false;
}
}