VS2013 MVC
首先自定义类CustomAttribute 继承 AuthorizeAttribute。 public class CustomAttribute : AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { var userSession = filterContext.HttpContext.Session['UserMsg']; if(filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute),true)) { //action有AllowAnonymous属性 return; } else if (filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)) { //Controller有AllowAnonymous属性 return; } else if (userSession == null )//增加session值判断 { filterContext.HttpContext.Response.Redirect('/Home/Login'); } else { return; } } }
在需要保护的Action或Controller上面添加属性。 [CustomAttribute] public class HomeController : Controller { public ActionResult Index() { return View(); } [AllowAnonymous]//该属性可以让action不去做验证 public ActionResult Login() { return View(); } }
如果不需要做保护的页面,如登录页可以加上AllowAnonymous属性。