ASP.Net MVC Session和Cookies的簡單使用


目標:用Session和Cookies實現登陸信息保存和展現

Cookies實現:

 

Controller:

//把登陸用戶名存到cookies中
HttpCookie cook = new HttpCookie("cookusername", UserName.ToString());    
Response.Cookies.Add(cook);
View Code

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>
View Code

Session實現:

controller:

 

//登陸成功把用戶名存入session
 Session["username"] = UserName.ToString();
View Code

View:

 <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button"
                            aria-expanded="false">
                          <i class="fa fa-user-o fa-fw"></i>
                           @if (Session["username"]!= null)
                          {
                              @Session["username"].ToString();
                             }                                              
                             <span class="caret"></span>
                     </a>
View Code

在web.config設置Session過期時間

<system.web>
<sessionState mode="InProc" timeout="30"></sessionState>  <!--session過期時間設置-->
</system.web>
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM