4

Visual StudioでASP.NETプロジェクトを作成するときの既定のWebサイトテンプレートには、LoginViewにログインしたときにユーザーのユーザー名が表示されます。これをユーザーの名に置き換えたいと思います。私はこれをデータベースに保存しているので、Site.masterページで次のことを試しました(ページのonloadで):

    MembershipUser user = Membership.GetUser();
    string id = user.ProviderUserKey.ToString();
       SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
        try
        {
            using (connection)
            {
                using (SqlCommand con_get = new SqlCommand("SELECT firstname FROM x WHERE userId='" + id + "'", connection)) //Executes SQL command             
                {
                    try
                    {
                        connection.Open(); //Opens the database connection
                        using (SqlDataReader reader = con_get.ExecuteReader())
                        {
                            if (reader != null)
                            {
                                while (reader.Read())
                                {
                                    Label label1 = (Label)sender;
                                    label1.Text = reader["x"].ToString();
                                }
                            }
                        }
                    }
                    catch
                    {

                    }

                    finally
                    {
                        connection.Close(); //Closes the database connection
                    }
                }
            }
        }
        catch
        {

        }

現在、これは機能しません。また、送信者を使用せず、label1.Text = reader ["x"]。ToString();を使用しようとしました。しかし、それはうまくいきませんでした。

誰かが私がこれを機能させる方法について何か提案がありますか?

また、これは正しいアプローチですか?確かに、ファーストネームをロードし、ユーザーが別のページに移動するたびにこれをリロードしない(したがって、データベースに対するクエリの数を減らす)より効率的な方法がありますか?

4

1 に答える 1

1

最終的に遭遇するのは、ラベルがマスターページにあるという事実だと思います。

protected void Page_Load(object sender, EventArgs e)
{
   if(!Page.IsPostBack)
   {
      var welcomeLabel = Page.Master.FindControl("lblWelcome") as Label;
      SetName(welcomeLabel);
   }
}

手書きのログインパターンは次のとおりです。

protected void SetName(Label welcomeLabel)
{
    //this is the type of thing you'd probably wanna do in the Global.asax on session start
    if (Session["userName"] == null || !Login()) return; //session variable is empty and the login attempt failed, give up
    var usersName = Session["userName"].ToString();
    welcomeLabel.Text = usersName;
}
protected bool Login()
{
    const string query = "SELECT Name FROM Users WHERE Password = @Password AND UserName = @UserName";
    using (var conn = new SqlConnection(connectionString))
    {
        using (var comm = new SqlCommand(query, conn))
        {
            comm.CommandType = CommandType.Text;
            comm.Parameters.Add(new SqlParameter("@Password", password)); //or get this from a control or wherever
            comm.Parameters.Add(new SqlParameter("@UserName", userName)); //or get this from a control or wherever
            conn.Open();
            var name = (string)comm.ExecuteScalar();
            if (!string.IsNullOrEmpty(name))
            {
                Session["userName"] = name;
                return true;
            }
            //"Login information is wrong or user doesn't exist.
            return false;
        }
    }
}

したがって、ここで行っているのは、データベースでユーザー名とパスワードの一致を検索することだけです。ユーザー名は一意である必要があるため、主キーのように機能し、AND フィルターはパスワードがユーザー名と一致することを確認します。単純。

一般的に言えば、ユーザーに関する情報をもう少しセッションに保存して、価値のあるものにする必要があると思います。私は一般的に、必要なときにいつでもアクセスできるように、なんらかの形式のユーザー オブジェクトを作成し、ユーザー オブジェクトを介して適切にアクセスできるようにします。それが Windows メンバーシップ クラスが支援しようとしているものだと思いますが、Windows 認証を行わない限り、それらを使用したくありません。しかし、それは単なる好みです。

于 2012-09-04T19:59:06.787 に答える