登錄時記住用戶名和密碼及cookie案例應用
登錄樣子,可以參考某一論壇的登錄介面:
記住這些信息,可以使用Cookie來實現(xiàn),更多Cookie應用,可參考
http://jb51.net/article/33590.htm
http://jb51.net/article/33591.htm
現(xiàn)在我們來模擬一個登錄介面:
<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的過期時間??梢詤⒖枷旅娴牡卿浭录a:
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;
}
}
}
看看操作演示,演示中有三種狀態(tài)演示,第一種是沒有點選CheckBox,這樣的話,關閉窗口,下次再打開時,沒有記住登錄的信息。
第二是點選擇了CheckBox,這樣下次再打開窗口,還可以看到帳號與密碼存儲在相應的文本框中,這都是Cookie沒有過期。
第三種,再點一次登錄,沒有點選remember me的CheckBox,這樣系統(tǒng)又移除了Cookie:

相關文章
.NET Core 3.0 可回收程序集加載上下文的實現(xiàn)
這篇文章主要介紹了.NET Core 3.0 可回收程序集加載上下文的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-06-06
談談如何在ASP.NET Core中實現(xiàn)CORS跨域
本篇文章主要介紹了如何在ASP.NET Core中實現(xiàn)CORS跨域,CORS主要是解決Ajax跨域限制的問題,有興趣的可以了解一下。2016-12-12
VS2019下opencv4.1.2配置圖文教程(永久配置)
這篇文章主要介紹了VS2019下opencv4.1.2配置圖文教程,文中安裝步驟介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-11-11
Global.asax的Application_Error實現(xiàn)錯誤記錄/錯誤日志的代碼
本文為大家介紹下利用Global.asax的Application_Error實現(xiàn)錯誤記錄,具體如下,有此需求的朋友可以參考下,希望對大家有所幫助2013-08-08

