C#Static helper class - 访问cookie

时间:2014-02-18 18:05:08

标签: c# cookies membership

我在我的网站上为表单授权实现了一个自定义cookie:

http://msdn.microsoft.com/en-us/library/system.web.security.formsauthenticationticket.aspx

由于我正在存储一些其他信息 userData

Account account = accountRepository.GetAccount(model.Email);
string userData = string.Format("{0}|{1}", account.UserId, account.AccountTypeId);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                                                                model.Email,
                                                                DateTime.Now,
                                                                DateTime.Now.AddMinutes(48),
                                                                model.RememberMe,
                                                                userData,
                                                                FormsAuthentication.FormsCookiePath);

我正在考虑创建一个静态助手类来从我的cookie中提取 userData

但我不能在控制器外部使用 User.Identity.Name

如何访问我的控制器?成为一个静态类是不对的?

由于

1 个答案:

答案 0 :(得分:0)

我的方法是按照最初的计划创建一个静态助手类:

public static class CookieHelper
{
    public static Guid GetCurrentUserId(IIdentity identity)
    {
        Guid result;

        var userData = ((FormsIdentity)identity).Ticket.UserData;

        result = new Guid(userData.Split('|')[0]);

        return result;

    }

    public static int GetCurrentAccountTypeId(IIdentity identity)
    {
        int result;

        var userData = ((FormsIdentity)identity).Ticket.UserData;

        result = Convert.ToInt16((userData.Split('|')[1]));

        return result;

    }
}

在我的控制器中,我这样称呼它:

Guid currentUserId = CookieHelper.GetCurrentUserId(User.Identity);