在MVC中定義本身的權限特性。json
下例中是簡單的登陸判斷,登陸信息存與Session中,若是Session中沒有登陸信息,那麼就不經過。app
在處理無權限的時候,判斷當前請求是否爲Ajax請求,若是是Ajax請求,返回Json {state=-1,msg="請登陸"},如過不是Ajax請求那麼就直接重定向到登陸頁面。ide
/// <summary> /// 受權特性 /// </summary> public class MyAuthorizeAttribute : AuthorizeAttribute { string errcode = null; /// <summary> /// 受權核心 /// </summary> /// <param name="httpContext"></param> /// <returns></returns> protected override bool AuthorizeCore(HttpContextBase httpContext) { var loginInfo = httpContext.Session["login"]; if (loginInfo == null) { errcode = "NotLoggedIn"; return false; } // 登陸用戶信息 UserIdentity userIdentity = new UserIdentity((AdminInfo)loginInfo); httpContext.User = new UserPrincipal(userIdentity); return true; } /// <summary> /// 處理無權限請求 /// </summary> /// <param name="filterContext"></param> protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { // 沒有登陸 if (errcode == "NotLoggedIn") { if (filterContext.HttpContext.Request.IsAjaxRequest()) { filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.OK; filterContext.Result = new JsonResult { ContentEncoding = System.Text.Encoding.UTF8, ContentType = "application/json", JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = new { state = -1, msg = "請從新登陸" }, }; } else { filterContext.Result = new RedirectResult("/Account/Login"); } } return; } }