簡體   English   中英

C#靜態幫助器類-訪問cookie

[英]C# Static helper class - Accessing cookies

我在我的網站上為表單授權實現了自定義Cookie:

http://msdn.microsoft.com/zh-CN/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

我如何才能將其替換為我的控制器? 成為靜態類是錯誤的嗎?

謝謝

我的方法是按照最初的計划創建Static Helper類:

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM