简单的谈一下MVC的Form认证。web
在作MVC项目时,用户登陆认证须要选用Form认证时,咱们该怎么作呢?下面咱们来简单给你们说一下。ide
首先说一下步骤spa
一、用户登陆时,若是校验用户名密码经过后,须要调用FormsAuthentication.SetAuthCookie()这个方法。code
二、用户退出时,须要调用FormsAuthentication.SignOut();方法orm
三、在配置文件web.config中,system.web 节点下, 配置<authentication mode="Forms"/> blog
四、校验:HttpContext.User.Identity.IsAuthenticated,若是是false,则没有经过认证,若是是true,则经过了认证继承
以上这三部,便可完成用户登陆的Form认证了。get
好了,下面咱们来看一下具体的代码。(View中的代码就不贴了,只贴Controller中的代码吧)权限控制
一、创建一个用于用户登陆用的Modelstring
1 public class LoginViewModel 2 { 3 [DisplayName("用户名")] 4 public string UserName { get; set; } 5 [DisplayName("密码")] 6 public string Password { get; set; } 7 }
二、创建登陆用的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: LogOut 15 public ActionResult LogOut() 16 { 17 FormsAuthentication.SignOut(); 18 return RedirectToAction("Index", "Login"); 19 } 20 }
三、创建一个登陆后,用户跳转的页面与Controller
1 public class MainController : BaseController 2 { 3 // GET: Main 4 public ActionResult Index() 5 { 6 return View(); 7 } 8 }
四、登录后跳转的页面的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 else 13 { 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 else 22 { } 23 */ 24 } 25 } 26 }
这个BaseController很简单,大致的做用就是,方式继承这个BaseController的控制器,当执行其下面的Action时,会进行Form校验,若是校验成功,则……,若是校验不成功则……,
登录后的页面的Controller都会继承BaseController,这样,就不用在每一个Controller中的Action重复的写Form认证的代码了。
是否是很简单?
固然,具体的细节问题这里都没有涉及到,这里只是简单的给你们介绍一下Form认证的使用,具体的细节问题,你们能够参考园中的大神们的博文。