我正在从 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);
}
提前致谢。
最佳答案
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 中的属性
至于考虑,请务必阅读项目页面底部的注释,因为它描述了为什么只应将其用于少量长期数据。
关于c# - 如何在 FormsAuthentication cookie 中存储附加数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14758708/