MVC用户验证

MVC提供了四种Filter(钩子),用于在Action执行之前或者之后,我们能够做一些事情,比如说判断有没有登录,比如说判断有没有权限。

IAuthorizationFilter:在所有Filter和Action执行之前执行

IActionFilter:分别在Action执行之前和之后执行。

IResultFilter:分别在Action Result执行之后和之前

IExceptionFilter:只有在filter,或者 action method, 或者 action result 抛出一个异常时候执行

做登录验证,用IAuthorizationFilter应该是最好的选择,比如系统自带的登陆与权限验证,就是用这个做的。但是我们今天要讲的是如何用ActionFilter做登录的验证。

我们转到Controller的定义的时候,发现是这样子的:

public abstract class Controller : ControllerBase, IActionFilter, IAuthorizationFilter, IDisposable, IExceptionFilter, IResultFilter, IAsyncController, IController, IAsyncManagerContainer

看到IActionFilter接口了木有,这让我们找到一个思路:新建一个基类,在该类中重载OnActionExecuting方法,这样子整个在所有Action执行之前都会先判断权限了:

public class BaseControllerfalse : Controller
{
//system.web.mvc
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Request.Cookies["UserID"] == null)
{
if (this.RouteData.Values["Controller"].ToString() != "Login")
{
//跳转到登陆页
filterContext.Result = new RedirectResult("/Login/Index");
}
}
base.OnActionExecuting(filterContext);
}
}

如上代码通过判断Cookies中的UserID来判断用户是否登陆,如果没有登陆,就跳转到Login/Index中去。你将其它所有需要验证登陆的controller继承自baseController就可以实现判断登陆了。

但是LoginController只能够直接继承自Controller,否则程序判断你没有登陆,然后跳转到Login,但是在Login实现Index之前,程序判断你仍然没有登陆,于是又跳转到Login,实现了一个死循环。

原文地址:https://www.cnblogs.com/jinhaoObject/p/4518829.html