如果您使用 FormsAuthentication 编写身份验证 cookie,则无需解密和读取原始 cookie 值。您可以@User.Identity.Name
在您的视图中使用。
public ActionResult AddNewUser(MemberRegisterModel mm)
{
...
FormsAuthentication.SetAuthCookie(mm.UserName, true || false);
...
return Redirect("Index", "Home");
}
Hello, and welcome, <strong>@User.Identity.Name</strong>
这就是 SetAuthCookie 内部的样子:
public static void SetAuthCookie(string userName, bool createPersistentCookie)
{
FormsAuthentication.Initialize();
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie,
FormsAuthentication.FormsCookiePath);
}
public static void SetAuthCookie(string userName, bool createPersistentCookie,
string strCookiePath)
{
FormsAuthentication.Initialize();
HttpContext current = HttpContext.Current;
if (!current.Request.IsSecureConnection && FormsAuthentication.RequireSSL)
throw new HttpException(System.Web.SR.GetString("Connection_not_secure_creating_secure_cookie"));
bool flag = CookielessHelperClass.UseCookieless(current, false, FormsAuthentication.CookieMode);
HttpCookie authCookie = FormsAuthentication.GetAuthCookie(userName, createPersistentCookie, flag ? "/" : strCookiePath, !flag);
if (!flag)
{
HttpContext.Current.Response.Cookies.Add(authCookie);
current.CookielessHelper.SetCookieValue('F', (string) null);
}
else
current.CookielessHelper.SetCookieValue('F', authCookie.Value);
}
private static HttpCookie GetAuthCookie(string userName, bool createPersistentCookie, string strCookiePath, bool hexEncodedTicket)
{
FormsAuthentication.Initialize();
if (userName == null)
userName = string.Empty;
if (strCookiePath == null || strCookiePath.Length < 1)
strCookiePath = FormsAuthentication.FormsCookiePath;
DateTime utcNow = DateTime.UtcNow;
DateTime expirationUtc = utcNow.AddMinutes((double) FormsAuthentication._Timeout);
FormsAuthenticationTicket ticket = FormsAuthenticationTicket.FromUtc(2, userName, utcNow, expirationUtc, createPersistentCookie, string.Empty, strCookiePath);
string str = FormsAuthentication.Encrypt(ticket, hexEncodedTicket);
if (str == null || str.Length < 1)
throw new HttpException(System.Web.SR.GetString("Unable_to_encrypt_cookie_ticket"));
HttpCookie httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, str);
httpCookie.HttpOnly = true;
httpCookie.Path = strCookiePath;
httpCookie.Secure = FormsAuthentication._RequireSSL;
if (FormsAuthentication._CookieDomain != null)
httpCookie.Domain = FormsAuthentication._CookieDomain;
if (ticket.IsPersistent)
httpCookie.Expires = ticket.Expiration;
return httpCookie;
}
请注意,它实际上确实创建了一个表单身份验证票证并加密了 cookie,