FormsAuthentication - handling a change of usernam

2019-03-26 03:22发布

问题:

My ASP.NET MVC web application allows administrators to change their own, or other users' usernames.

Users are logged in by calling FormsAuthentication.SetAuthCookie(userName [string], createPersistentCookie [bool]). They are logged out by calling FormsAuthentication.SignOut(). I understand that after updating the username I'd need to sign them out and back in again. But how do I retrieve the existing value of createPersistentCookie? e.g. how do I retain their original 'remember me' setting when signing them back in?

回答1:

var cookieName = FormsAuthentication.FormsCookieName;
var request = HttpContext.Current.Request;
var cookie = request.Cookies.Get(cookieName);
if (cookie == null)
    return;

try
{
    var ticket = FormsAuthentication.Decrypt(cookie.Value);

    //This should give you what you want...
    bool isPersistent = ticket.IsPersistent;
}
catch (Exception ex)
{
    //Logging
}