企业管理系统开发笔记(4)---后台登录_MVC过滤器

在asp.net时代,我们通常需要在后台的每个页面进行判断用户是否登录的状态,不管是通过session还是通过windows身份验证还是表单验证方式等等方法来对用户登录进行判断跳转。但是在mvc时代,我们就没必要这么麻烦了。我们可以通过设置其过滤器的方式实现。

首先,我们需要写一个自定义个control类。重写父类的OnActionExecuting方法。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace YPF.CMS.UI.Controllers
{
    public class BaseController : Controller
    {
        //
        // GET: /Base/
        /// <summary>
        ///  自定义校验  session
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //在过滤器上下文中判断是否存在登录后的session对象,没有就进行跳转
            if (Session["UserInfo"]==null)
            {
                filterContext.HttpContext.Response.Redirect("/Login/index");
            }
            base.OnActionExecuting(filterContext);
        }

    }
}

其次,使其他的控制器全部继承该类。

最后,我们就在实现了在页面请求来了之后,会先进入过滤器进行判断。这里我们只进行了session的判断。当然也可以其他的判断和设置。

原文地址:https://www.cnblogs.com/ypfnet/p/4137993.html