如何使用当前用户在母版页中登录

时间:2016-07-22 05:40:10

标签: c# asp.net

如何使用当前用户登录?当前用户将显示在默认主页的母版页中,母版页中的标签将继承到母版页的内容页面。

这是我的登录页面asp代码:

<div class="container-fluid">

<form class="form-signin" runat="server">
    <h1 class="form-signin-heading text-muted">Sign In</h1>
    <asp:TextBox ID ="email" runat="server" CssClass="form-control" placeholder="Email Address"></asp:TextBox>
    <asp:TextBox ID ="password" runat="server" CssClass="form-control" placeholder="Password" TextMode="Password"></asp:TextBox>
    <br />

    <asp:Button ID="btnLogIN" runat="server" CssClass="btn btn-primary btn-block" Text="Log In" OnClick="btnLogIN_Click" />

</form>

我的aspx.cs代码在这里,我不知道这是否正确。

protected void btnLogIN_Click(object sender, EventArgs e)
    {
        Utility u = new Utility();
        string conn = u.connect();
        SqlConnection connUser = new SqlConnection(conn);
        SqlCommand read = connUser.CreateCommand();
        SqlDataReader reader = null;

        int empid = 0;
        string dbuser = "";
        string dbpword = "";

        string username = email.Text;
        string passwords = password.Text;

        string login = "Select * from MOSEFAccount where UserName = '" + username + "' AND Password = '" + passwords + "'";

        try
        {
            connUser.Open();
            read.CommandText = login;
            reader = read.ExecuteReader();
        }
        catch
        {
            Console.WriteLine("Error");
        }
        while (reader.Read())
        {
            empid = reader.GetInt32(0);
            dbuser = reader.GetString(1);
            dbpword = reader.GetString(2);
        }

        if (username == dbuser && passwords == dbpword)
        {

            Response.Redirect("~/Default.aspx?ID=" + empid);
        }
        else
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append(@"<script type ='text/javascript'>");
            sb.Append("alert('Invalid Account');");
            sb.Append(@"</script>");
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "EditHideModalScript", sb.ToString(), false);
        }
        connUser.Close();
    }

1 个答案:

答案 0 :(得分:0)

您能详细说明当前用户的含义吗?除非您登录,否则您不是登录用户而是匿名用户。

更新

将提取的数据存储在Session对象中,并随时随地访问它。例如: 有关存储详细信息,请使用: -

if (username == dbuser && passwords == dbpword)
{
    Session["UserName"] = username;
    Session["EmpId"] = empid;
    Response.Redirect("~/Default.aspx?ID=" + empid);
}

用于显示用途(在母版页中):

<%=Session["UserName"]%>
<%=Session["EmpId"]%>

您可以在此基础上构建一个User类,然后创建此类的实例并将实例本身存储在Session中。