1.新建LoginRequestFilter类
public class LoginRequestFilter : System.Web.Mvc.ActionFilterAttribute
{
public bool IsCheck { get; set; } = true;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (IsCheck)
{
if (HasLogin(filterContext))
{
base.OnActionExecuting(filterContext);
}
else
{
filterContext.HttpContext.Response.Redirect("/Login/Index");
}
}
else
{
base.OnActionExecuting(filterContext);
}
}
private bool HasLogin(ActionExecutingContext filterContext)
{
HttpContextBase httpContext = filterContext.HttpContext;
if (httpContext.Session["UserName"] == null || httpContext.Session["Pwd"] == null)
{
return false;
}
return true;
}
}
2.FilterConfig设置全局验证
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
//注册全局过滤器验证
filters.Add(new LoginRequestFilter());
}
}
3排除登陆方法,让其不验证
[LoginRequestFilter(IsCheck =false)]
public class LoginController : BaseController
{
public ActionResult Index()
{
return View();
}
/// <summary>
/// 测试界面
/// </summary>
/// <returns></returns>
public ActionResult Test()
{
return View();
}
}