.net MVC使用Session驗證用戶登錄(4)
更新時間:2018年04月10日 10:55:21 作者:清幽火焰
這篇文章主要為大家詳細介紹了.net MVC使用Session驗證用戶登錄的相關資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下
用最簡單的Session方式記錄用戶登錄狀態(tài)
1.添加DefaultController控制器,重寫OnActionExecuting方法,每次訪問控制器前觸發(fā)
public class DefaultController : Controller { protected override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; var userName = Session["UserName"] as String; if (String.IsNullOrEmpty(userName)) { //重定向至登錄頁面 filterContext.Result = RedirectToAction("Index", "Login", new { url = Request.RawUrl}); return; } } }
2.登錄控制器
public class LoginController : Controller { // GET: Login public ActionResult Index(string ReturnUrl) { if (Session["UserName"] != null) { return RedirectToAction("Index", "Home"); } ViewBag.Url = ReturnUrl; return View(); } [HttpPost] public ActionResult Index(string name, string password, string returnUrl) { /* 添加驗證用戶名密碼代碼 */ Session["UserName"] = name; if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("http://") && !returnUrl.StartsWith("/\\")) { return Redirect(returnUrl); } else { return RedirectToAction("Index", "Home"); } } // POST: /Account/LogOff [HttpPost] public ActionResult LogOff() { Session["UserName"] = null; return RedirectToAction("Index", "Home"); } }
3.需要驗證的控制器繼承DefaultController
public class HomeController : DefaultController { public ActionResult Index() { return View(); } }
這種方式適合比較小的項目
優(yōu)點:簡單,易開發(fā)
缺點:無法記錄登錄狀態(tài),而且Session方式容易丟失
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
詳解ASP.NET-----Repeater數(shù)據(jù)控件的用法總結
本篇文章主要介紹了ASP.NET--Repeater數(shù)據(jù)控件的用法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。2016-11-11用Html5與Asp.net MVC上傳多個文件的實現(xiàn)代碼
Html 5 的有一些File API,對Form表單增強的特性,讓我們輕松支持多文件上傳,看下面的Html片斷代碼2012-08-08