ASP.NET MVC、表单身份验证和会话

发布于 2024-11-18 05:31:30 字数 359 浏览 3 评论 0 原文

我想在用户登录时执行以下行,以便我可以访问 MembershipUser 对象。但是我很难弄清楚何时设置它。

 Session["User"] = Membership.GetUser();

到目前为止,我已经尝试过...

  • Application_AcquireRequestState
  • Application_BeginRequest
  • FormsAuthentication_OnAuthenticate

对于每个会话状态不一定可用。

在登录页面中手动调用它很容易,但我也需要在使用 cookie 自动登录时让它工作。

I would like to execute the below line when the user logs in so that I have access to the MembershipUser object. However I am having a hard time figuring out when to set it.

 Session["User"] = Membership.GetUser();

So far I've tried...

  • Application_AcquireRequestState
  • Application_BeginRequest
  • FormsAuthentication_OnAuthenticate

For each the session state isn't necessarily available.

Manually calling it in the log-in page is easy, but I need to have it work when automatically logging in using cookies as well.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

山川志 2024-11-25 05:31:30

如果您想要做的只是将任意数据与用户名一起存储,有一个名为 FormsAuthenticationExtensions 的开源项目,它允许您以非常简单的方式完成此操作:

在您的登录操作中,您可以存储您的像这样的数据:

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

然后像这样读回它:

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

数据存储在保存身份验证票证的同一个 cookie 中,因此只要用户登录,它就可用。

项目页面: http://formsauthext.codeplex.com/

Nuget:http:// /nuget.org/List/Packages/FormsAuthenticationExtensions

If all you want do is store arbitrary data along with the username, there is an open source project called FormsAuthenticationExtensions that allows you to do exactly this in a very simple manner:

In your Login action you would store your data like this:

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

And you read it back like this:

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

Data is stored in the same cookie holding the authentication ticket, so it will be available for as long as the user is logged in.

Project page: http://formsauthext.codeplex.com/

Nuget: http://nuget.org/List/Packages/FormsAuthenticationExtensions

勿忘初心 2024-11-25 05:31:30

为什么?您可以从任何地方访问 Membership.GetUser。这是一个静态方法。将可以从任何地方访问的值放在可以从任何地方访问的地方有什么意义?

Why? You can access Membership.GetUser from anywhere. It's a static method. What is the point of placing a value you can access from anywhere in a place you can access from anywhere?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文