如何在 FormsAuthentication cookie 中存储附加数据?

问题描述 投票:0回答:2

我正在从 URL 中检索租户名称。我宁愿只执行一次,将其存储在 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);
    } 

提前致谢。

c# asp.net-mvc-4 cookies forms-authentication
2个回答
14
投票

codeplex 和 Nuget 上的 FormsAuthenticationExtensions 项目正是这样做的。 https://archive.codeplex.com/?p=formsauthext

使用-设定值

using FormsAuthenticationExtensions;
using System.Collections.Specialized;

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

用法-检索值

using FormsAuthenticationExtensions;
using System.Web.Security;

var ticketData = ((FormsIdentity) HttpContext.Current.User.Identity).Ticket.GetStructuredUserData();
var name = ticketData["name"];
var emailAddress = ticketData["emailAddress"];

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

此外,这里没有发生“黑魔法”,它只是将 UserData 属性的设置/检索封装在 FormsAuthentication Ticket 中

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


7
投票

就我个人而言,我不会尝试更改 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

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

var cookie = Request.Cookies["myCookie"];
var tenantName = cookie.Values["TenantName"].ToString();
//tenantName = "myTenantName"
© www.soinside.com 2019 - 2024. All rights reserved.