标签:
ASP.MVC上实现权限控制的方法很多,比如使用AuthorizeAttribute这个特性
public class AuthorizeDiy : AuthorizeAttribute { /// <summary> /// 提供一个入口用于自定义授权检查 /// </summary> /// <param name="httpContext"></param> /// <returns></returns> protected override bool AuthorizeCore(HttpContextBase httpContext) { bool pass = false; HttpCookie cookie = HttpContext.Current.Request.Cookies["admin"]; if (cookie == null || cookie.Value == null) { httpContext.Response.StatusCode = 401; pass = false; } else { pass = true; } return pass; } /// <summary> /// 处理未能授权的Http请求 /// </summary> /// <param name="filterContext"></param> protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { base.HandleUnauthorizedRequest(filterContext); filterContext.HttpContext.Response.Write(filterContext.HttpContext.Response.StatusCode); if (filterContext.HttpContext.Response.StatusCode == 401) { //跳转到登录界面 filterContext.Result = new RedirectResult("/Login"); } } }
重写2个方法用于验证处理授权请求和授权失败。
[AuthorizeDiy] public class BaseAdminController:Controller { }
注意使用自定义特性
/// <summary> /// 登录控制器 /// </summary> public class LoginController : BaseAdminController { // // GET: /Login/ [AllowAnonymous] public ActionResult Index() { return View(); } [HttpPost] [AllowAnonymous] public JsonResult LoginCheck() { FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, "admin", DateTime.Now, DateTime.Now.AddDays(1), true, Newtonsoft.Json.JsonConvert.SerializeObject(new {name="test"})); string ticString = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie("admin", ticString); Response.Cookies.Add(cookie); object result = new { success = true }; return this.Json(result); } }
注意:继承基类,并且使用MVC自定义特性进行授权此处只是简单实现。注意:跳转登录和验证登录的2个action必须使用Allowanonymous特性否则登录界面的权限验证无法通过会出现重复定向多次的错误
登录视图:
@{ ViewBag.Title = "Index"; } <script src="~/Scripts/jquery-1.8.2.min.js"></script> <h2>这个是登录界面</h2> <form class="formClass"> <button>登录</button> </form> <script> $(function () { $(".formClass").submit(function () { $.post("/Login/LoginCheck", {}, function (r) { alert(JSON.stringify(r)); if (r) { location.href = "/Home/Index"; } else { alert("登录失败"); } }); return false; }) }) </script>
主视图:
@{ ViewBag.Title = "Index"; } <script src="~/Scripts/jquery-1.8.2.min.js"></script> <h2>Index</h2> <script> $(function () { }) </script>
主页控制器:
public class HomeController : BaseAdminController { // // GET: /Home/ public ActionResult Index() { return View(); } }
先正常操作,然后清空缓存,实现权限控制效果,MVC路由指向Home控制器的Index
当进入主页时发现未授权自动跳转至登录界面
ASP.MVC 基于AuthorizeAttribute权限设计案例
标签:
原文地址:http://www.cnblogs.com/CallmeYhz/p/5941478.html