MVC利用ActionFilterAttribute全局过滤器验证用户登录

我们之前用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();
    }

    public ActionResult Details(int id)
    {
        return View();
    }

    public ActionResult Create()
    {
        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= "用户名或密码错误!" });
            }
            else if (userList[0].IsDelete == 1)
            {
                return Json(new { state = "error", message = "该用户已被禁用!" });
            }
            else if (userList[0].Password != password)
            {
                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>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules>
  </system.web>
</configuration>

 

  • 5
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

changuncle

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值