Cookie或会话以及如何开始

时间:2011-06-30 06:17:52

标签: asp.net session cookies

Heey Stackoverflow,

我有一个问题即时开始学习asp.net语言csharp我有以下登录代码我的问题是如何开始或我在哪里可以学习写下会话cookie而不是我可以回到其他页面再次读取这个cookie的用户名和密码非常匹配

public partial class Administratie : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {

        try
        {
            string cnnString = ConfigurationManager.ConnectionStrings["Stefan"].ConnectionString;

            using (SqlConnection con = new SqlConnection(cnnString))
            using (SqlCommand cmd = new SqlCommand("select [Username],[Password] from Admin where [Username] = @Username and [Password] = @Password", con))
            {
                string Username = (textUsername.Text.Length > 0) ? textUsername.Text : null;
                string Password = (TextPassword.Text.Length > 0) ? TextPassword.Text : null;

                cmd.Parameters.Add("@Username", System.Data.SqlDbType.VarChar).Value = textUsername.Text;
                cmd.Parameters.Add("@Password", System.Data.SqlDbType.VarChar).Value = TextPassword.Text;

                con.Open();

                using (SqlDataReader dr = cmd.ExecuteReader())
                {
                    if (dr.Read())
                        if (Page.IsValid)
                    {                     

                        // Login Succeed 
                        // Response.Redirect("Admin.aspx");







                    }
                }
            }



        }
        catch (Exception) { }

        // Login Failed
        Response.Write("Wrong Username ");
    }
}

2 个答案:

答案 0 :(得分:1)

试试看:

Create and retrieve Cookie data (C#)

阅读Cookie:

  HttpCookie cookie = Request.Cookies["Preferences"];
  if (cookie == null)
  {
    lblWelcome.Text = "<b>Unknown Customer</b>";
  }
  else
  {
    lblWelcome.Text = "<b>Cookie Found.</b><br><br>";
    lblWelcome.Text += "Welcome, " + cookie["Name"];
  }

设置Cookie

  HttpCookie cookie = Request.Cookies["Preferences"];
  if (cookie == null)
  {
    cookie = new HttpCookie("Preferences");
  }

  cookie["Name"] = txtName.Text;
  cookie.Expires = DateTime.Now.AddYears(1);
  Response.Cookies.Add(cookie);

如果您想在会话中存储数据,只需设置它:

Session["username"]=username;

并阅读:

string username=Session["username"];

答案 1 :(得分:0)

您可以使用会话存储用户名和密码。如果您想使用“记住我”选项,您可以在cookie中保存用户名和密码。

请检查使用sessioncookies

的链接