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

标签 c# asp.net-mvc-4 cookies forms-authentication

我正在从 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/

相关文章:

javascript - 使用cloudflare缓存动态页面

c# - 编程语言中的构造函数

c# - Mongo C# 驱动程序 - 使用嵌套动态构建过滤器

c# - 使用 SharpDX 绘制 SVG 图形

c# - 以单一 mp4 格式复制 m3u8 段文件

asp.net-mvc-4 - 子操作输出缓存与 FIPS 不兼容吗?

php - 将用户名存储在 cookie 中安全吗?

c# - 从 Entity Framework 查询转换到 NHibernate 时遇到问题

asp.net-mvc-4 - 使用 RTM 调试 MVC4 捆绑

javascript - 如何在 Angular 2 中为 jwt token 设置 cookie