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");
    }
 
  }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM