MVC在基控制器中實現處理Session的邏輯

來源:互聯網
上載者:User

標籤:style   blog   http   color   資料   os   

當需要跨頁面共用資訊的時候,Session是首當其衝的選擇,最典型的例子就是:在處理登入和購物車邏輯的時候需要用到Session。在MVC中,可以把處理Session的邏輯放在一個泛型基控制器中,但需要注意的是:在判斷沒有登入就跳轉到登入頁的時候,需要把出錯控制器和登入控制器排除在外。

using System.Collections.Generic;using System.Web.Mvc;using System.Web.Routing;namespace MvcApplication1.Controllers{    public class BaseController<TModel> : Controller    {        private const string loginSession = "LoginSession";        private const string shoppingCartSession = "ShoppingCartSession";        private const string errorController = "Error";        private const string LoginController = "Login";        private const string LoginAction = "Login";        //沒有登入的跳轉到登入頁        protected override void Initialize(RequestContext requestContext)        {            base.Initialize(requestContext);            //如果沒有登入,且不是出錯和登入控制器就跳轉到登入頁            if (!NoNeedSessionController(requestContext) && !HasLoginSession())            {                GoToAction(requestContext, Url.Action(LoginAction, LoginController));            }        }        //對哪些不需要依賴緩衝的控制器 返回true        private bool NoNeedSessionController(RequestContext requestContext)        {            //從路由資料中取到當前controller的名稱            var c = requestContext.RouteData.Values["controller"].ToString().ToLower();            //把不需要依賴Session的控制器名稱放到列表中            var noNeedSessionList = new List<string>            {                errorController.ToLower(),                LoginController.ToLower()            };            return noNeedSessionList.Contains(c);        }        //跳轉到某個視圖        private void GoToAction(RequestContext requestContext, string action)        {            requestContext.HttpContext.Response.Clear();            requestContext.HttpContext.Response.Redirect(action);            requestContext.HttpContext.Response.End();        }        //登入的時候判斷是否有Session        protected bool HasLoginSession()        {            return Session[loginSession] != null;        }        //判斷購物車是否有Session        protected bool HasShoppingCartSession()        {            return Session[shoppingCartSession] != null;        }        //從Session中擷取登入模型的執行個體        protected TModel GetLoginModelFromSession()        {            return (TModel)this.Session[loginSession];        }        //從Session中擷取購物車模型的執行個體        protected TModel GetShoppingCartModelFromSession()        {            return (TModel)this.Session[shoppingCartSession];        }        //設定登入Session        protected void SetLoginSession(TModel loginModel)        {            Session[loginSession] = loginModel;        }        //設定購物車Session        protected void SetShoppingCartSession(TModel shoppingCartModel)        {            Session[shoppingCartSession] = shoppingCartModel;        }        //讓登入Session失效        protected void AbandonLoginSession()        {            if (HasLoginSession())            {                Session.Abandon();            }        }        //讓購物車Session失效        protected void AbandonShoppingCartSession()        {            if (HasShoppingCartSession())            {                Session.Abandon();            }        }    }}

讓其他控制器派生於基控制器:

using System.Web.Mvc;using MvcApplication1.Models;namespace MvcApplication1.Controllers{    public class LoginController : BaseController<LoginModel>    {        public ActionResult Index()        {            //把登入模型執行個體儲存到Session中            LoginModel loginModel = new LoginModel();            SetLoginSession(loginModel);            //從Session中擷取登入模型執行個體            LoginModel sessioModel = GetLoginModelFromSession();            //使登入Session失效            AbandonLoginSession();            return View();        }    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.