根据提供的附加信息,您希望使用 FormsAuthentication 票证存储附加数据。为此,您需要首先创建一个自定义 FormsAuthentication 票证:
存储数据
获取当前的HttpContext(不用担心可测试性)
var httpContext = HttpContext.Current;
确定票证何时到期:
var expires = isPersistent
? DateTime.Now.Add(FormsAuthentication.Timeout)
: NoPersistenceExpiryDate; // NoPersistenceExpiryDate = DateTime.MinValue
创建新的 FormsAuthentication 票证来保存您的自定义数据。
var authenticationTicket = new FormsAuthenticationTicket(
1,
username,
DateTime.Now,
DateTime.Now.Add(FormsAuthentication.Timeout),
isPersistent,
"My Custom Data String"); //Limit to about 1200 bytes max
创建您的 HTTP cookie
new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authenticationTicket))
{
Path = FormsAuthentication.FormsCookiePath,
Domain = FormsAuthentication.CookieDomain,
Secure = FormsAuthentication.RequireSSL,
Expires = expires,
HttpOnly = true
};
最后添加到响应中
httpContext.Response.Cookies.Add(cookie);
检索数据
然后您可以通过解析存储的身份验证票证来检索后续请求的数据...
再次获取当前的 HttpContext
var httpContext = HttpContext.Current
检查请求是否已通过身份验证(调用 Application_AuthenticateRequest 或 OnAuthorize)
if (!httpContext.Request.IsAuthenticated)
return false;
检查您是否有可用的 FormsAuthentication 票证并且该票证尚未过期:
var formsCookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
if (formsCookie == null)
return false;
检索 FormsAuthentication 票证:
var authenticationTicket = FormsAuthentication.Decrypt(formsCookie.Value);
if (authenticationTicket.Expired)
return false;
最后检索您的数据:
var data = authenticationTicket.UserData;