如何在表单身份验证中传输键值对?

时间:2012-03-23 21:11:03

标签: c# asp.net-mvc cookies forms-authentication

在我的登录页面中,我创建了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;
    }
}

但是获取String.Empty而不是我输入的userId。

为什么?

1 个答案:

答案 0 :(得分:0)

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

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