MVC的AuthorizeAttribute
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); // filters.Add(new PermissionAttribute()); } }
public class PermissionAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { var isAuthorized = false; if (httpContext != null && httpContext.Session != null) { if (HttpContext.Current.Session["UserName"] != null) { isAuthorized = true; } } return isAuthorized; } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { filterContext.Result = new RedirectResult("~/Account/Login"); } }
[Permission] public class HomeController : Controller { public ActionResult Index() { ViewBag.Message = "欢迎使用 ASP.NET MVC!"; return View(); } public ActionResult About() { return View(); } }
-- 20211027补充
private static bool SkipAuthorization(AuthorizationContext filterContext) { Contract.Assert(filterContext != null); return filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true); }
//登录检测 if (!SessionHelper.IsLogin) { if (filterContext.HttpContext.Request.IsAjaxRequest()) { filterContext.HttpContext.Response.StatusCode = 500; filterContext.Result = new JsonResult() { Data = new BaseReponseJson() { Msg = "请重新登录" }, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } else { Utils.GotoLogin(filterContext); } return; }