登入時記住使用者名稱和密碼及cookie案例應用

來源:互聯網
上載者:User

登入樣子,可以參考某一論壇的登入介面:

記住這些資訊,可以使用Cookie來實現,更多Cookie應用,可參考
http://jb51.net/article/33590.htm
http://jb51.net/article/33591.htm
現在我們來類比一個登入介面:

複製代碼 代碼如下:<table>
<tr>
<td style="width: 15%; text-align: right;">
User Name
</td>
<td>
<asp:TextBox ID="TextBoxUserName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td style="text-align: right;">
Password
</td>
<td>
<asp:TextBox ID="TextBoxPassword" TextMode="Password" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td style="text-align: right;">
Remember me
</td>
<td>
<asp:CheckBox ID="CheckBoxRememberMe" runat="server" />
</td>
</tr>
<tr>
<td style="text-align: right;">
</td>
<td>
<asp:Button ID="ButtonLogin" runat="server" Text="Login" OnClick="ButtonLogin_Click" />
</td>
</tr>
</table>

運行時的效果:

我們要判斷使用者在點銨鈕的Click事件時,是否有選擇Remember me這個CheckBox,如果選中了,要把這個登入的資訊記錄至Cookie,還要把Cookie的到期時間設定7天之後到期。反之,只把登入的資訊記錄入Cookie之中,不設定Cookie的到期時間。可以參考下面的登入事件代碼:

複製代碼 代碼如下:protected void ButtonLogin_Click(object sender, EventArgs e)
{
Response.Cookies["Name"].Expires = DateTime.Now.AddDays(-1);
Response.Cookies["Password"].Expires = DateTime.Now.AddDays(-1);

if (CheckBoxRememberMe.Checked)
{
Response.Cookies["Name"].Expires = DateTime.Now.AddDays(7);
Response.Cookies["Password"].Expires = DateTime.Now.AddDays(7);
}

Response.Cookies["Name"].Value = this.TextBoxUserName.Text.Trim();
Response.Cookies["Password"].Value = this.TextBoxPassword.Text.Trim ();
}

接下來,你還得在Page_load中去讀取Cookie.複製代碼 代碼如下:protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.Cookies["Name"] != null && Request.Cookies["Password"] != null)
{
this.TextBoxUserName.Text = Request.Cookies["Name"].Value;
this.TextBoxPassword.Attributes["value"] = Request.Cookies["Password"].Value;
}
}
}

看看操作示範,示範中有三種狀態示範,第一種是沒有點選CheckBox,這樣的話,關閉視窗,下次再開啟時,沒有記住登入的資訊。

第二是點選擇了CheckBox,這樣下次再開啟視窗,還可以看到帳號與密碼儲存在相應的文字框中,這都是Cookie沒有到期。

第三種,再點一次登入,沒有點選remember me的CheckBox,這樣系統又移除了Cookie:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.