【4】 .net MVC使用Session驗證用戶登錄


用最簡單的Session方式記錄用戶登錄狀態

1.添加DefaultController控制器,重寫OnActionExecuting方法,每次訪問控制器前觸發

    public class DefaultController : Controller
    {
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;

            var userName = Session["UserName"] as String;
            if (String.IsNullOrEmpty(userName))
            {
                //重定向至登錄頁面
                filterContext.Result = RedirectToAction("Index", "Login", new { url = Request.RawUrl});
                return;
            }

        }
    }

2.登錄控制器

    public class LoginController : Controller
    {
        // GET: Login
        public ActionResult Index(string ReturnUrl)
        {
            if (Session["UserName"] != null)
            {
                return RedirectToAction("Index", "Home");
            }
            ViewBag.Url = ReturnUrl;
            return View();
        }

        [HttpPost]
        public ActionResult Index(string name, string password, string returnUrl)
        {
            /*
                添加驗證用戶名密碼代碼
            */
            Session["UserName"] = name;
            if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        // POST: /Account/LogOff
        [HttpPost]
        public ActionResult LogOff()
        {
            Session["UserName"] = null;
            return RedirectToAction("Index", "Home");
        }
    }

3.需要驗證的控制器繼承DefaultController

    public class HomeController : DefaultController
    {
        public ActionResult Index()
        {
            return View();
        }
    }

 


這種方式適合比較小的項目
優點:簡單,易開發
缺點:無法記錄登錄狀態,而且Session方式容易丟失


免責聲明!

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



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