开发者

ASP.NET MVC, Forms Authentication, and Session

开发者 https://www.devze.com 2023-03-16 15:33 出处:网络
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.

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开发者_StackOverflow();

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.


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


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号