MVC使用Controller完成登录验证

高效的方法:使用Controller进行登录验证

1.  新建一个用于验证的Controller父类,并在其内重写OnActionExecuting方法完成登陆校验:

using System.Web.Mvc;
 
namespace PMS.WebApp.Controllers
{
  public class FilterController : Controller
  {
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
      base.OnActionExecuting(filterContext);
      if (Session["user"] == null)
      {
        //filterContext.HttpContext.Response.Redirect("/User/Login");
        filterContext.Result = Redirect("/User/Login");
      }
    }
  }
}

  

在Controller校验类的OnActionExecuting方法中,有如下代码

//filterContext.HttpContext.Response.Redirect("/User/Login");
filterContext.Result = Redirect("/User/Login");      

我们使用后者而放弃前者的原因是,ASP.NET MVC中规定,Action必须返回ActionResult,如果使用前者,在完成跳转前会先进入到请求的页面,这样不符合我们使用过滤器的初衷。

2.  然后使需要校验的Controller继承于我们定义的校验Controller即可完成全局登录校验操作:

using System.Web.Mvc;
using PMS.IBLL;
 
namespace PMS.WebApp.Controllers
{
  public class UserController : FilterController//Controller
  {
    //
    // GET: /User/
    //private IUserService _userService;
    //private IUserService UserService
    //{
    //  get { return _userService ?? (_userService = new UserService()); }
    //  set { _userService = value; }
    //}
    private IUserService UserService { get; set; }
    //[CheckLogin]
    public ActionResult Index()
    {
      return Content("OK");
    }
 
  }
}

  

认真工作、认真生活,努力做最好的自己!!!
原文地址:https://www.cnblogs.com/songhuihui/p/12666609.html