如何在FormsAuthentication cookie中存储其他数据?

bas*_*bas 7 c# cookies forms-authentication asp.net-mvc-4

我正在从网址中检索租户名称.我更喜欢只做一次,将它存储在cookie中,并在新页面请求中需要时从那里检索它.

我使用下面的代码来"创建"一个cookie.我希望界面允许我存储其他信息,但事实并非如此.有没有办法做到这一点,还是我走错了路?

    public void SignIn(string userName, bool createPersistentCookie)
    {
        if (String.IsNullOrEmpty(userName))
            throw new ArgumentException("Value cannot be null or empty.", "userName");

        FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
    } 
Run Code Online (Sandbox Code Playgroud)

提前致谢.

Tom*_*mmy 12

Codeplex和Nuget上的FormsAuthenticationExtensions项目就是这样做的. http://formsauthext.codeplex.com/

用法 - 设置值

using FormsAuthenticationExtensions;
using System.Collections.Specialized;

var ticketData = new NameValueCollection
{
    { "name", user.FullName },
    { "emailAddress", user.EmailAddress }
};
new FormsAuthentication().SetAuthCookie(user.UserId, true, ticketData);
Run Code Online (Sandbox Code Playgroud)

用法 - 检索值

using FormsAuthenticationExtensions;
using System.Web.Security;

var ticketData = ((FormsIdentity) HttpContext.Current.User.Identity).Ticket.GetStructuredUserData();
var name = ticketData["name"];
var emailAddress = ticketData["emailAddress"];
Run Code Online (Sandbox Code Playgroud)

基本上,您可以在FormsAuthentication cookie中附加名称/值字典来存储一些常用值.我们利用这个商店存储一小部分用户信息,例如companyId等.

此外,这里没有"黑魔法"发生,它只是封装了FormsAuthentication Ticket中UserData属性的设置/检索功能.

至于考虑,请务必阅读项目页面底部的注释,因为它描述了为什么这只应用于少量长寿数据.


For*_*Two 6

就个人而言,我不会尝试改变Auth Cookie.而是创建一个新的cookie:

var myCookie = new HttpCookie("myCookie");//instantiate an new cookie and give it a name
myCookie.Values.Add("TenantName", "myTenantName");//populate it with key, value pairs
Response.Cookies.Add(myCookie);//add it to the client
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样读取写在cookie上的值

var cookie = Request.Cookies["myCookie"];
var tenantName = cookie.Values["TenantName"].ToString();
//tenantName = "myTenantName"
Run Code Online (Sandbox Code Playgroud)