简体   繁体   中英

How to redirect or visit page if only there is a logged in user

I have three pages ( Home, Register, Store )linked with each other. The home page offers log in option against a pre existing user saved in database. Someone can visit the Store page if only the log in successful, otherwise clicking in the Store page do nothing, (just stick in the same Home page).

Home.aspx.cs:

  protected void Button1_Click(object sender, EventArgs e)//login
    {
        SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\lab1.mdf;Integrated Security=True");
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "SELECT * FROM userdata WHERE username='" + TextBox1.Text + "'";
        cmd.Connection = conn;
        //cmd.ExecuteNonQuery();

        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        if (dt.Rows.Count > 0)
        {
            //Session["name"] = dt.Rows[0]["userName"].ToString();
            Response.Redirect("Store.aspx?name=" + TextBox1.Text + "");
        }
        else
        {
            Response.Redirect("Register.aspx");
        }
    }

Home.aspx:

 <p><a href="Home.aspx">Home</a> <a href="Register.aspx">Register</a> <a href="Store.aspx">Store</a></p>

Store.aspx:

 <p><a href="Home.aspx">Home</a> <a href="Register.aspx">Register</a> <a href="Store.aspx">Store</a></p>

there are two ways one is to create a class and define a static field and other way is session but i would prefer session for login

first you will create a session eg

if (dt.Rows.Count > 0)
        {

            Response.Redirect("Store.aspx?name=" + TextBox1.Text + "");
            Session["UserAuthentication"] = true;
        }

and now check on every page or if you have master page in the .cs file add code to check weather UserAuthentication if true or not and remember to add code into the Page_Load of the cs file

add a check

 if (Convert.ToBoolean(Session["UserAuthentication"]) == false)
    {
        Response.Redirect("Register.aspx");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM