MVC在基控制器中实现处理Session的逻辑

时间:2023-03-09 16:15:47
MVC在基控制器中实现处理Session的逻辑

当需要跨页面共享信息的时候,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();
} }
}