MVC 4 simple membership. How to check is somebody

2019-02-27 15:17发布

问题:

I'm new in mvc 4 and can't understand exactly how simple membership worked. After all configuration I put this code to AccountController to see how it works and is it work at all

string UserName1 = WebSecurity.CurrentUserName;
bool LoginResult= WebSecurity.Login("admin", "111111");
string UserName2 = WebSecurity.CurrentUserName;
WebSecurity.Logout();

And when I run debugger I see that after all finished

UserName1 = "" 
LoginResult = true 
UserName2 = ""

Everything is ok except UserName2. Why it is empty? Login was sussess... Also I can't see UserID at WebSecurity and WebSecurity.IsAuthentificated is false Why login was successful but WebSecurity do not shows it at all?

回答1:

Login does not do what you think it does. It does not immediately set the current user, instead it sets a cookie on the users web browser, and on the next page refresh, asp.net will recognize that cookie and give them an authenticated request.

This is not specific to simple membership, that's how all authentication works in asp.net. Once authenticated, the page has to be refreshed for a login to be recognized.