get username after login

﹥>﹥吖頭↗ 提交于 2019-12-25 07:25:06

问题


I want to get the username after login but it doesn't work.

public partial class Login : System.Web.UI.Page
    {
        string strUser;

        protected void Login1_LoggedIn(object sender, EventArgs e)
        {
            strUser = Membership.GetUser().UserName;

            Response.Redirect("Home");
        }
        protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
        {
            strUser = Membership.GetUser().UserName;
            Response.Redirect("Home");
        }
    }

This is my error:


回答1:


Membership.GetUser().UserName is null, because the new principal object is not attached to the current HttpContext object yet.

So you need to explicitly retrieve that recently logged-in user using username from Login control.

Update: Credit to jadarnel27

protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
  // Get the username from login control and retrieves the user info explicitly
  Membership user = Membership.GetUser(Login1.Username); 
  ...
}



回答2:


You need to check and make sure the user's login was successful. It looks like you're just using standard ASP.NET membership, so this should work:

protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
    if(e.Authenticated)
    {
        strUser = Membership.GetUser().UserName;
        Response.Redirect("Home");
    }
    else
    {
        strUser = "Login Failed!";
    }
}

It's been a while since I worked with these controls, but you might need to determine the value of e.Authenticated yourself first and set it. If so, you need to put this before the if-block I wrote above:

bool authenticated = Membership.ValidateUser(Login1.UserName, Login1.Password);
e.Authenticated = authenticated;

I think vanilla ASP.NET membership handles that part for you; if you were using a custom authentication scheme, you would definitely need to do that step.



来源:https://stackoverflow.com/questions/15633645/get-username-after-login

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!