Как передать пару ключ-значение на formAuthentication? - PullRequest
1 голос
/ 24 марта 2012

На моей странице входа я создаю файл cookie FA.

Я хочу добавить к нему идентификатор пользователя.

Затем я перенаправляю на страницу по умолчанию,

Где я хочу прочитать идентификатор пользователя.

Я использую эти два вспомогательных метода:

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 вместо введенного мной идентификатора пользователя.

Почему?

1 Ответ

0 голосов
/ 24 марта 2012

Вы создаете новый authcookie с FormsAuthentication.GetAuthCookie вместо чтения того, который идет с запросом.Попробуйте это:

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