1. 程式人生 > >MVC中Session的使用和傳遞

MVC中Session的使用和傳遞

error gin ati val addm then ont tex new

1.登錄時在controller中記錄session,代碼如下:

 public ActionResult Login(UserLoginViewModel uViewModel)
        {
            if (ModelState.IsValid)
            {
                var user = db.ADUsers.SingleOrDefault(t => t.usrName == uViewModel.usrName && t.usrPassword == uViewModel.usrPassword);

                
if (user != null) { FormsAuthentication.SetAuthCookie(uViewModel.usrName, false);//將用戶名放入Cookie中 System.Web.HttpContext.Current.Session["usrName"] = uViewModel.usrName; //將用戶名放入session中 return RedirectToAction("Index","Home"); }
else { ModelState.AddModelError("usrName", "用戶名不存在!"); } } return View(uViewModel); }

2.在View中,可以根據session進行判斷是否正常登錄

@if (Session["usrName"] != null)
{
    using (Html.BeginForm("LogOff", "ADUsers", FormMethod.Post, new
{ id = "logoutForm", @class = "navbar-right" })) { @Html.AntiForgeryToken() <ul class="nav navbar-nav navbar-right"> <li> @Html.ActionLink("你好," + Session["usrName"] + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" }) </li> <li><a href="javascript:document.getElementById(‘logoutForm‘).submit()">註銷</a></li> </ul> } } else { <ul class="nav navbar-nav navbar-right"> <li>@Html.ActionLink("登錄", "Login", "ADUsers", routeValues: null, htmlAttributes: new { id = "loginLink" })</li> <li>cookies:@Session["usrName"];</li> </ul>

3.註銷時,記得將session清空

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            System.Web.HttpContext.Current.Session["usrName"] = null;
            return RedirectToAction("Login");
        }

MVC中Session的使用和傳遞