从登录控件获取用户名并存储在数据库C#中

时间:2016-03-10 06:32:13

标签: c# asp.net get username

我是.NET的新手,目前正在构建一个网站,注册用户可以在其中上传文档,管理员可以查看上传的文档。 我使用登录控件来使用存储过程验证用户。 现在我希望当用户登录并上传文档时,他的名字也应该存储在数据库中(@Cname列),所以我试图从loginName控件中获取标签中的用户名

这是login.aspx页面代码

asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
        <asp:Login ID="Login1" runat="server" OnAuthenticate="ValidateUser" BackColor="#F7F6F3" BorderColor="#E6E2D8" BorderPadding="4" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" Font-Size="0.8em" ForeColor="#333333" Height="256px" Width="536px">
        <InstructionTextStyle Font-Italic="True" ForeColor="Black" />
        <LoginButtonStyle BackColor="#FFFBFF" BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" Font-Size="Large" ForeColor="#284775" Height="34px" Width="100px" />
        <TextBoxStyle Font-Size="X-Large" />
        <TitleTextStyle BackColor="#5D7B9D" Font-Bold="True" Font-Size="Large" ForeColor="White" />
    </asp:Login>    
</asp:Content>  

我正在尝试这个并且发送System.Web.UI.WebControls.LoginName错误

string aa =Convert.ToString(LoginName1);
Label5.text = aa;

Login.aspx.cs代码是

protected void ValidateUser(object sender, EventArgs e)
        {
            int userId = 0;
            string roles = string.Empty;

            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("Validate_User"))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@Username", Login1.UserName);
                    cmd.Parameters.AddWithValue("@Password", Login1.Password);
                    cmd.Connection = con;
                    con.Open();
                    SqlDataReader reader = cmd.ExecuteReader();
                    reader.Read();
                    userId = Convert.ToInt32(reader["UserId"]);
                    roles = reader["Roles"].ToString();
                    con.Close();
                }
                switch (userId)
                {
                    case -1:
                        Login1.FailureText = "Username and/or password is incorrect.";
                        break;
                    case -2:
                        Login1.FailureText = "Account has not been activated.";
                        break;
                    default:
                        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, Login1.UserName, DateTime.Now, DateTime.Now.AddMinutes(2880), Login1.RememberMeSet, roles, FormsAuthentication.FormsCookiePath);
                        string hash = FormsAuthentication.Encrypt(ticket);
                        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);

                        if (ticket.IsPersistent)
                        {
                            cookie.Expires = ticket.Expiration;
                        }
                        Response.Cookies.Add(cookie);
                        Response.Redirect(FormsAuthentication.GetRedirectUrl(Login1.UserName, Login1.RememberMeSet));
                        break;
                }
            }
        }

验证用户存储过程

USE [LoginDB]
GO
/****** Object:  StoredProcedure [dbo].[Validate_User]    Script Date: 3/10/2016 10:37:39 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--[Validate_User] 'Mudassar', '12345'
ALTER  PROCEDURE [dbo].[Validate_User]
    @Username NVARCHAR(20),
    @Password NVARCHAR(20)
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @UserId INT, @LastLoginDate DATETIME, @RoleId INT

    SELECT @UserId = UserId, @LastLoginDate = LastLoginDate, @RoleId = RoleId 
    FROM Users WHERE Username = @Username AND [Password] = @Password

    IF @UserId IS NOT NULL
    BEGIN
        IF NOT EXISTS(SELECT UserId FROM UserActivation WHERE UserId = @UserId)
        BEGIN
            UPDATE Users
            SET LastLoginDate =  GETDATE()
            WHERE UserId = @UserId

            SELECT @UserId [UserId], 
                    (SELECT RoleName FROM Roles 
                     WHERE RoleId = @RoleId) [Roles] -- User Valid
        END
        ELSE
        BEGIN
            SELECT -2 [UserId], '' [Roles]-- User not activated.
        END
    END
    ELSE
    BEGIN
        SELECT -1 [UserId], '' [Roles] -- User invalid.
    END
END

如何获取用户名?请帮忙

1 个答案:

答案 0 :(得分:0)

在登录控件

Login控件中的控件无法直接加入,但您需要使用该控件内的FindControl找到它们,例如:

TextBox txtUserName = (TextBox)Login1.FindControl("UserName");

如果您在登录控件上看不到这一行

<asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">User Name:</asp:Label>
<asp:TextBox ID="UserName" runat="server" CssClass="textEntry"></asp:TextBox>

然后你需要转换它并查看它的<LayoutTemplate>...</LayoutTemplate>

在其他页面上

要在其他网页上获取用户信息,请使用Membership.GetUser(),您可以使用Membership.GetUser().UserName作为用户名