如何在formAuthentication上传输键值对

本文关键字:传输 键值对 formAuthentication | 更新日期: 2023-09-27 18:28:54

在我的登录页面中,我创建了FA cookie。

我想添加userId。

然后我重定向到我的默认页面,

我想读取userId的位置。

我使用这两种辅助方法:

public static class NewWebHelpers
{
    public static void CreateAuthCookie(string cookieName, string cookieValue)
    {
        //Get ASP.NET to create a forms authentication cookie (based on settings in web.config)~
        HttpCookie cookie = FormsAuthentication.GetAuthCookie(cookieName, false);
        //Decrypt the cookie
        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
        //Create a new ticket using the details from the generated cookie, but store the username &
        //token passed in from the authentication method
        FormsAuthenticationTicket newticket = new FormsAuthenticationTicket(
        ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration,
        ticket.IsPersistent, cookieValue);
        // Encrypt the ticket & store in the cookie
        cookie.Value = FormsAuthentication.Encrypt(newticket);
        // Update the outgoing cookies collection.
        System.Web.HttpContext.Current.Response.Cookies.Set(cookie);
    }

    public static string ReadAuthCookie(string cookieName)
    {
        //Get ASP.NET to create a forms authentication cookie (based on settings in web.config)~
        HttpCookie cookie = FormsAuthentication.GetAuthCookie(cookieName, false);
        //Decrypt the cookie
        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
        return ticket.UserData;
    }
}

但是得到CCD_ 1而不是我输入的userId。

为什么?

如何在formAuthentication上传输键值对

您正在使用FormsAuthentication.GetAuthCookie创建一个新的authcookie,而不是读取请求附带的authcookie。试试这个:

public static string ReadAuthCookie(string cookieName)
{
    HttpCookie cookie =   
        HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
    return ticket.UserData;
}