標籤:protect 執行 sys 認證 名稱 dex div 使用者名稱 return
簡單的談一下MVC的Form認證。
在做MVC項目時,使用者登入認證需要選用Form認證時,我們該怎麼做呢?下面我們來簡單給大家說一下。
首先說一下步驟
1、使用者登入時,如果校正使用者名稱密碼通過後,需要調用FormsAuthentication.SetAuthCookie()這個方法。
2、使用者退出時,需要調用FormsAuthentication.SignOut();方法
3、在設定檔web.config中,system.web 節點下, 配置<authentication mode="Forms"/>
4、校正:HttpContext.User.Identity.IsAuthenticated,如果是false,則沒有通過認證,如果是true,則通過了認證
以上這三部,即可完成使用者登入的Form認證了。
好了,下面我們來看一下具體的代碼。(View中的代碼就不貼了,只貼Controller中的代碼吧)
1、建立一個用於使用者登入用的Model
1 public class LoginViewModel2 {3 [DisplayName("使用者名稱")]4 public string UserName { get; set; }5 [DisplayName("密碼")]6 public string Password { get; set; }7 }
2、建立登入用的Controller與頁面,其中Controller裡面有登入與退出兩個Action
1 public class LoginController : Controller 2 { 3 // GET: Login 4 public ActionResult Index(LoginViewModel loginViewModel) 5 { 6 if (loginViewModel.UserName == "admin" && loginViewModel.Password == "123456") 7 { 8 FormsAuthentication.SetAuthCookie(loginViewModel.UserName, false); 9 return RedirectToAction("Index", "Main");10 }11 return View();12 }13 14 //GET: LogOut15 public ActionResult LogOut()16 {17 FormsAuthentication.SignOut();18 return RedirectToAction("Index", "Login");19 }20 }
3、建立一個登入後,使用者跳轉的頁面與Controller
1 public class MainController : BaseController2 {3 // GET: Main4 public ActionResult Index()5 {6 return View();7 }8 }
4、登陸後跳轉的頁面的Controller是繼承的BaseController,那麼BaseController是怎麼寫的呢?
1 public class BaseController : Controller 2 { 3 protected override void OnActionExecuting(ActionExecutingContext filterContext) 4 { 5 base.OnActionExecuting(filterContext); 6 //登入認證處理 7 if (!filterContext.HttpContext.User.Identity.IsAuthenticated) 8 { 9 //未登入10 Response.Redirect("~/Login/Index");11 }12 else13 {14 //已登入,Action級許可權控制處理15 var controllerName = filterContext.RouteData.Values["controller"].ToString();//控制器名稱16 var actionName = filterContext.RouteData.Values["action"].ToString(); //Action名稱17 //根據controllerName與actionName進行許可權檢查18 /*19 if()20 { }21 else22 { }23 */24 }25 }26 }
這個BaseController很簡單,大體的作用就是,方式繼承這個BaseController的控制器,當執行其下面的Action時,會進行Form校正,如果校正成功,則……,如果校正不成功則……,
登陸後的頁面的Controller都會繼承BaseController,這樣,就不用在每個Controller中的Action重複的寫Form認證的代碼了。
是不是很簡單?
當然,具體的細節問題這裡都沒有涉及到,這裡只是簡單的給大家介紹一下Form認證的使用,具體的細節問題,大家可以參考園中的大神們的博文。
淺談MVC Form認證