.net MVC使用Session驗證用戶登錄(4)
用最簡單的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方式容易丟失
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后臺管理系統(tǒng)之前端頁面框架構(gòu)建源碼分享
- asp.net CommunityServer中的wwwStatus
- .Net Core簡單使用Mvc內(nèi)置的Ioc(續(xù))
- .Net Core簡單使用Mvc內(nèi)置的Ioc
- Spring.Net控制反轉(zhuǎn)IoC入門使用
- ASP.NET Core應(yīng)用中與第三方IoC/DI框架的整合
- MVC使用Spring.Net應(yīng)用IOC(依賴倒置)學(xué)習(xí)筆記3
- .net MVC使用IPrincipal進(jìn)行Form登錄即權(quán)限驗證(3)
- .NET Unity IOC框架使用實例詳解
相關(guān)文章
asp.net下檢測遠(yuǎn)程URL是否存在的三種方法
檢測遠(yuǎn)程URL是否存在的三種方法,需要的朋友可以參考下。2009-12-12asp.net導(dǎo)出Excel顯示中文亂碼的解決方法
asp.net導(dǎo)出Excel顯示中文亂碼的解決方法,需要的朋友可以參考一下2013-03-03詳解ASP.NET-----Repeater數(shù)據(jù)控件的用法總結(jié)
本篇文章主要介紹了ASP.NET--Repeater數(shù)據(jù)控件的用法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。2016-11-11用Html5與Asp.net MVC上傳多個文件的實現(xiàn)代碼
Html 5 的有一些File API,對Form表單增強(qiáng)的特性,讓我們輕松支持多文件上傳,看下面的Html片斷代碼2012-08-08