標籤:分享 使用 -o http exp 簡單 state out .net
目標:用Session和Cookies實現登陸資訊儲存和展現
Cookies實現:
Controller:
1 1 //把登陸使用者名稱存到cookies中2 2 HttpCookie cook = new HttpCookie("cookusername", UserName.ToString()); 3 3 Response.Cookies.Add(cook);
View:
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"> <i class="fa fa-user-o fa-fw"></i> @if (Request.Cookies["cookusername"]!= null) { @Request.Cookies["cookusername"].Value; } <span class="caret"></span> </a>
Session實現:
controller:
1 //登陸成功把使用者名稱存入session2 Session["username"] = UserName.ToString();
View:
1 <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button"2 aria-expanded="false">3 <i class="fa fa-user-o fa-fw"></i>4 @if (Session["username"]!= null)5 {6 @Session["username"].ToString();7 } 8 <span class="caret"></span>9 </a>
在web.config設定Session到期時間
<system.web><sessionState mode="InProc" timeout="30"></sessionState> <!--session到期時間設定--></system.web>
ASP.Net MVC Session和Cookies的簡單使用