简体   繁体   English

登录asp.net后如何检索当前用户的用户名

[英]how to retrive the username of the current user after login in asp.net

I need to get the user current name after a log in. I need to display the name in the page, like welcome user . 登录后,我需要获取用户的当前名称。我需要在页面中显示该名称,例如welcome user Please help me, my current code is given below 请帮助我,我的当前代码如下

protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con1"].ConnectionString);
        con.Open();
        SqlCommand cmdr = new SqlCommand("Select name,password From registration", con);
        SqlDataReader dr = cmdr.ExecuteReader();
        while (dr.Read())
        {
            if (txt_name.Text == dr[0].ToString() && txt_pass.Text == dr[1].ToString())
            {
                Response.Redirect("logout.aspx");
            }
            else
            {
                label4.Text ="Invalid Username/Password";
            }
        }

    }

If you're using the ASP.NET membership : 如果您使用的是ASP.NET成员资格

string userName = Membership.GetUser().UserName

However, obviously you are not using it (i strongly recommend). 但是,显然您没有使用它(强烈建议)。 Why do you redirect to logout.aspx when the user successfully provided his username and password? 用户成功提供用户名和密码后,为什么要重定向到logout.aspx

Apart from that you're not using the provided informatiuons at all in your query. 除此之外,您在查询中根本没有使用提供的信息。

SqlCommand cmdr = new SqlCommand("Select name,password From registration", con);

So you should use parameters to filter for the correct record: 因此,您应该使用参数来筛选正确的记录:

using(var cmdr = new SqlCommand("Select name,password From registration where name=@name and password=@password", con))
{
    cmdr.Parameters.AddWithValue("@name", userName);
    cmdr.Parameters.AddWithValue("@password", password);
    if(cmdr.ExecuteReader().HasRows)
    {
        // user + password correct
    }
    else
    {
        // user or password incorrect
    }
}

Membership.GetUser().UserName in a membership provider. 成员资格提供程序中的Membership.GetUser()。UserName。 Under no circumstances should you run the code you have there. 在任何情况下都不应运行那里的代码。 It is asking for a hack. 它要求黑客入侵。 You should not be loading the passwords into memory and you are going to have performance issues as you gain more users because of your loop through all users! 您不应该将密码加载到内存中,并且由于遍历所有用户而获得更多用户时,您将遇到性能问题!

protected void Button1_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con1"].ConnectionString);
    con.Open();
    SqlCommand cmdr = new SqlCommand("Select name,password From registration", con);
    SqlDataReader dr = cmdr.ExecuteReader();
    while (dr.Read())
    {
        if (txt_name.Text == dr[0].ToString() && txt_pass.Text == dr[1].ToString())
        {
            Session["UserName"]=dr[0].ToString(); // OR Session["UserName"]=txt_name.Text;
            Response.Redirect("logout.aspx");
        }
        else
        {
            label4.Text ="Invalid Username/Password";
        }
    }

} }

You can fetch the session values in HTML(if your using it in your application) 您可以获取HTML中的会话值(如果您在应用程序中使用了会话值)

<div>
Welcome <%=HttpContext.Current.Session["UserName"]%>
</div>

You should be able to get the identity of the user from the User property in code-behind. 您应该能够从隐藏代码的User属性中获取用户的身份。

myLabel.Text = User.Identity.Name;

The full namespace etc. for this is HttpContext.Current.User.Identity.Name . 完整的名称空间等是HttpContext.Current.User.Identity.Name

Reference for HttpContext.User property: http://msdn.microsoft.com/en-us/library/system.web.httpcontext.user.aspx HttpContext.User属性的参考: http : //msdn.microsoft.com/zh-cn/library/system.web.httpcontext.user.aspx

put the username in a session 将用户名放入会话中

Session["username"] = dr[0].ToString();

then on the other page 然后在另一页上

if Session["username"] != null
{
  String username = Session["username"].ToString();
}
else
{
  Page.Redirect("login.aspx");
}

You can check each different page 您可以检查每个不同的页面

You should ideally use built-in ASP.NET Forms Authentication - see this article for quick start. 理想情况下,您应该使用内置的ASP.NET表单身份验证-有关快速入门,请参阅此文章 Coming to your question, on successful login, you should use line such as 谈到您的问题,成功登录后,您应该使用诸如

FormsAuthentication.RedirectFromLoginPage(txt_name.Text, true);

This would store the user name into authentication cookie and which can be subsequently retrieved using code such as User.Identity.Name that you can user anywhere in your pages. 这会将用户名存储到身份验证cookie中,随后可以使用诸如User.Identity.Name代码来检索该用户名,您可以在页面的任何位置使用它。

You can store the username in session object and get username anywhere in the application if session is present 您可以将用户名存储在会话对象中,如果存在会话,则可以在应用程序中的任何位置获取用户名

But you have to update your query also, The way you are calling is not good approach 但是您还必须更新查询,调用方式不是一种好方法

protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con1"].ConnectionString);
        con.Open();
        SqlCommand cmdr = new SqlCommand("Select name From registration where name = @username and password = @password", con);
        cmdr.Parameters.Add("@username", txt_name.Text.trim());
        cmdr.Parameters.Add("@password", txt_pass.Text.trim());

        SqlDataReader dr = cmdr.ExecuteReader();

        if(cmdr.ExecuteReader().HasRows)
        {
             Response.Redirect("logout.aspx");
             Session["userName"] = txt_name.Text.trim();
        }
        else{
        //Error page path
        }               
        //DOn't forget to close the connection when you Open it
      con.Close();
    }

You should learn more from some tutorials: 您应该从一些教程中了解更多信息:

  1. http://csharp-station.com/Tutorial/AdoDotNet/Lesson01 http://csharp-station.com/Tutorial/AdoDotNet/Lesson01
  2. MSDN MSDN

..并且如果您只想使用User对象:

var username = User.Identity.Name;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Asp.Net Boilerplate ,,如何获取当前登录用户? - Asp.Net Boilerplate,, How to Get current Login User? 如何在ViewComponent Asp.Net Core中获取当前登录用户 - How get current login user in ViewComponent Asp.Net Core asp.net中的登录控件如何保留当前用户的信息? - login control in asp.net how to keep information of current user? 如何在Asp.Net MVC中获得比当前用户名更多的用户名信息 - How to get more information than username about current user in Asp.Net MVC ASP.NET 核心 - 如何在登录时使用用户名获取特定用户的角色 - ASP.NET Core - How to get the Role of a particular user using his username at the point of Login 使用ASP.NET登录后如何获取用户名和角色? (将aspnetdb集成到我的数据库中) - How to get username and role after login using ASP.NET? (integrated aspnetdb into my database) 在ASP.NET中提取当前用户名 - Pulling current username in ASP.NET 没有用户名的ASP.NET登录控件 - ASP.NET Login control without a Username 在asp.net mvc中注册成功后用户名自动填写登录页面(重定向到登录) - Username auto fill in Login Page after Register success (Redirect to Login) in asp.net mvc 在ASP.NET中尝试3次无效密码后如何阻止用户名 - How To Block The UserName After 3 Invalid Password Attempts IN ASP.NET
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM