通过两个自定义特性 ,实现统一登陆验证。
1. 用于登陆NeedLoginAttribute;
public class NeedLoginAttribute : ActionFilterAttribute
{
private static string _loginUrl = ConfigurationManager.AppSettings["LoginUrl"]?? "/Login";
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//判断Action方法的Control是否跳过登录验证
if (filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(SkipCheckLoginAttribute), false))
{
return;
}
//判断Action方法是否跳过登录验证
if (filterContext.ActionDescriptor.IsDefined(typeof(SkipCheckLoginAttribute), false))
{
return;
}
if (true)
{
filterContext.HttpContext.Response.Redirect(_loginUrl);
}
}
}
2. 免于登录UnNeedLoginAttribute;
public class UnNeedLoginAttribute : System.Attribute
{
}
3. 使用方式。
1)创建baseController,所有的控制器继承这个基类,这样就可以在访问action的时候先进行登陆验证了;
[NeedLogin]
public class BaseController : Controller
{}
2)但是,但是存在登陆页面的控制器继承了基类,但是又不希望登陆,因为本身不是登陆状态,验证登陆只会死循环。那么该怎么做呢?如下:
[UnNeedCheckLogin]
public class LoginController : BaseController
{}
到此,MVC的统一登陆验证就实现完毕!是不是很简单。