自定義一個受權篩選器類,繼承於AuthorizeAttribute:ide
using System; using System.Web; using System.Web.Mvc; namespace MvcApplication1 { public class DWAuthorizeAttribute : AuthorizeAttribute { /// <summary> /// 判斷用戶是否登陸 /// </summary> /// <param name="filterContext"></param> public override void OnAuthorization(AuthorizationContext filterContext) { HttpContextBase context = filterContext.HttpContext; if (context.Session["LoginUser"] == null) context.Response.Redirect("~/User/Login"); } } }
在需進行登陸驗證的Action上加約束:spa
[DWAuthorize] public ActionResult Index() { return View(); }