如何在asp.net注册后自动登录

时间:2015-08-20 08:42:00

标签: asp.net autologin

我希望在注册后使用会话 [" ud"]这样的会话自动,但我不知道在哪里我应该把它放进去。

public partial class index : System.Web.UI.Page
{
    SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings["dbpath"]);

    protected void btnSave_Click(object sender, EventArgs e)
    {
        long idx;
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = cnn;
        cmd.CommandText = "Insert into tblUser (UInfo,UEmail,UName,UPass, UGender) Values (@P1,@P2,@P3,@P4,@P5) select @@Identity";
        cmd.Parameters.AddWithValue("@P1", txtInfo.Text);
        cmd.Parameters.AddWithValue("@P2", txtEmail.Text);
        cmd.Parameters.AddWithValue("@P3", txtUserName.Text);
        cmd.Parameters.AddWithValue("@P4", txtPass.Text);
        cmd.Parameters.AddWithValue("@P5", rdbMale.Checked);
        cnn.Open();
        idx = Convert.ToInt64(cmd.ExecuteScalar()); // i think here we can do something
        cnn.Close();  

这里我们要上传用户的图像,它可以正常工作

        string fn = "";
        if (FileUpload1.HasFile == true)
        {
            fn = FileUpload1.FileName;
            string des = Server.MapPath("\\UserImg\\") + idx.ToString() + ".jpg";
            FileUpload1.PostedFile.SaveAs(des);

            SqlCommand cmdUpdate = new SqlCommand();
            cmdUpdate.Connection = cnn;
            cmdUpdate.CommandText = "Update tblUser Set UImg=@P5 where UId=@P0";
            cmdUpdate.Parameters.AddWithValue("@P5", idx.ToString() + ".jpg");
            cmdUpdate.Parameters.AddWithValue("@P0", idx);
            cnn.Open();
            cmdUpdate.ExecuteNonQuery();
            cnn.Close();
        }
        Response.Redirect("Profile.aspx");
    }
  }

1 个答案:

答案 0 :(得分:0)

在sql数据库中输入数据后,您将获得新用户的ID

 idx = Convert.ToInt64(cmd.ExecuteScalar()); // i think here we can do something

一旦你将id分配给你的会话

idx = Convert.ToInt64(cmd.ExecuteScalar()); // i think here we can do something
 cnn.Close();  
 Session["ud"]=idx;

一旦您分配了会话,您只需重定向到所需的页面并验证会话变量是否为空。

我希望在 Profile.aspx 页面上检查相同的会话变量。

Profile.aspx.cs - 页面加载

if (Session["ud"] != null)
                {
                    //successfull login
                }
                else
                {
                    //redirect to login page
                }