2011-06-30 36 views
1

Heey#1,餅乾或會話以及如何開始

我有一個問題,即時通訊開始學習asp.net語言CSHARP,我有以下登錄代碼我的問題是如何開始或我在哪裏可以學寫下來會話cookie,比我能回到另一個頁面,輸入用戶名和密碼沒有匹配TY非常再讀這個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 "); 
    } 
} 

回答

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"]; 
0

您可以使用會話來存儲用戶名和密碼。如果您想使用記住我的選項,您可以將用戶名和密碼保存在Cookie中。

請檢查使用鏈接sessioncookies