【转】MVC利用ActionFilterAttribute全局过滤器验证用户登录
作者:changuncle
来源:CSDN
原文:https://blog.csdn.net/xiaouncle/article/details/82990392
版权声明:本文为博主原创文章,转载请附上博文链接!
---------------------
我们之前用Webform开发的时候是通过创建BasePage类,来检查Session["UserId"]是否存在
/// <summary> /// 父类中定义一些公共的事情 /// </summary> public class BasePage : System.Web.UI.Page { //页面生命周期中Init事件对应的OnInit()方法 //OnInit()方法会先于PageLoad()方法执行 //OnInit()方法会在所有控件都已初始化且已应用所有外观设置后引发,使用该事件来读取或初始化控件属性 protected override void OnInit(EventArgs e) { //检查用户是否登录 if (Session["UserId"] == null) { //跳转到登录页面 } else { base.OnInit(e); } } }
MVC中是如何进行登陆校验的呢,继续往下看吧!
1、利用ActionFilterAttribute创建检查过滤器
public class LoginAttribute : System.Web.Mvc.ActionFilterAttribute { //表示是否检查登录 public bool IsCheck { get; set; } //Action方法执行之前执行此方法 public override void OnActionExecuting(ActionExecutingContext filterContext) { if (IsCheck) { if (this.HasLogin(filterContext)) { base.OnActionExecuting(filterContext); } else { //仅有这句话跳转时登陆界面会显示在iframe框架中 filterContext.HttpContext.Response.Redirect("/Login/Index"); } } else { base.OnActionExecuting(filterContext); } } private bool HasLogin(ActionExecutingContext filterContext) { if (filterContext.HttpContext.Session["UserId"] != null) { return true; } return false; } }
2、添加特性应用LoginAttribute
LoginAttribute特性创建完毕后,我们可以通过给方法或类加特性的方式进行应用,不过这样做的坏处很明显,就是如果有n个方法需要进行登陆校验那就必须对n个方法加上特性,LoginAttribute在实际中应用又很广泛,所以逐个去加特性虽然可用,但是挺麻烦。
[LoginAttribute(IsCheck =true)] public class UserManageController : Controller { public ActionResult Index() { return View(); } }
3、在Global.asax中注册全局过滤器
我们可以通过注册全局过滤器的方式来解决上述的问题。
Global.asax中通过调用FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);来为MVC程序注册全局过滤器,FilterConfig类在App_Start文件夹中(创建MVC项目时会自动生成),我们在RegisterGlobalFilters()添加要注册的过滤器
public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); //注册全局过滤器 filters.Add(new LoginAttribute() { IsCheck = true }); } }
4、对登陆方法进行特殊处理
因为在请求登陆界面及进行登陆时Session还为空,所以不能对其应用LoginAttribute,否则会造成循环调用,这时我们定义的IsCheck变量就派上用场了。
[LoginAttribute(IsCheck =false)] public class LoginController : Controller { public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(string username, string password) { using (LastChanceContext lastChance = new LastChanceContext()) { IList<Sys_User> userList = lastChance.Sys_User.Where(a => a.LoginName == username).ToList(); if (userList.Count < 1) { return Json(new { state= "error", message= "用户名或密码错误!" }); } ……………………(省略账号密码验证)………… Session["UserId"] = userList[0].UserId; Session["LoginName"] = userList[0].LoginName; Session["RealName"] = userList[0].RealName; return Json(new { state = "success", message = "" }); } } }
5、解决登陆界面嵌套在iframe框架中的问题
web开发中经常会有这种情况,主页面中包含侧边导航菜单和iframe,点击菜单项,对应页面会在iframe中显示,整个页面不会刷新,如果设置了会话Session,在会话过期后再操作会自动redirect重定向到登录页面。基于以上情况,经常会出现在session过期后,再点击菜单项,登录页面显示在iframe中而非显示在当前窗口的情况。
解决办法,在登录页面加上如下js代码:
$(document).ready(function () { //判断一下当前层是不是顶层,如果不是,则做一下顶层页面重定向 if (window != top) { top.location.href = location.href; } });
6、设置Session过期时间
我们是通过检查Session是否为空来判断用户登录是否有效,因此如何设置Session的过期时间还是有必要了解一下的。
<configuration> <system.web> <!--mode的默认值就是InProc,1表示1分钟--> <sessionState mode="InProc" timeout="1"></sessionState> </system.web> </configuration>
实战(MVC)
/// <summary> /// 基类 /// </summary> [BaseActionAttribute] public abstract class BaseController : Controller { Model.RoleAuthorize.Sys_Employee _userInfo; /// <summary> /// 获取用户信息 /// </summary> protected Model.RoleAuthorize.Sys_Employee UserInfo { get { if (_userInfo != null) { return _userInfo; } var model = this.HttpContext.Items["userSession"] as Model.RoleAuthorize.Sys_Employee; if (model == null || StringHelper.IsEmpty(model.Id)) return null; _userInfo = model; return model; } } } /// <summary> /// 请求验证 /// </summary> public class BaseActionAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), true).Any()) { base.OnActionExecuting(filterContext); return; } var sessionStr=filterContext.HttpContext.Session["login_session"] if (sessionStr == null) { filterContext.Result = new ContentResult() { Content = "<script>top.location.href = '/Login/Index'</script>", ContentType = "text/html" }; base.OnActionExecuting(filterContext); return; } var data=(T)sessionStr; if (data == null) { filterContext.Result = new ContentResult() { Content = "<script>top.location.href = '/Login/Index'</script>", ContentType = "text/html" }; base.OnActionExecuting(filterContext); return; } filterContext.HttpContext.Items["userSession"] = data; base.OnActionExecuting(filterContext); } }
登录退出处理
HttpContext.Session["login_session"] = value; HttpContext.Session.Remove("login_session");

浙公网安备 33010602011771号