標籤: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(); } }}