ASP.NET MVC, Forms Authentication, and Session
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?
精彩评论