用户成功登录后,其所参与的课题、在课题中所扮演的角色以及在课题中所有权限执行的操作等等信息,
通常的做法是保存在Session中,用时在从Session中取值,导致各方法与Session操作紧密关联,不方便调试,
项目中也有蛮多冗余代码。
最近,我开始维护某医院的随访系统,注意到它是这么处理的:
1) 使用IModelBinder接口自定义一个SessionModel的Binder类
public class SessionModelBinder : IModelBinder
{
private const string SessionKey = "_sessionmodel";
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
return GetSessionModel();
}
public static SessionModel GetSessionModel()
{
SessionModel sp = (SessionModel)HttpContext.Current.Session[SessionKey];
if (sp == null)
{
sp = new SessionModel();
HttpContext.Current.Session[SessionKey] = sp;
}
return sp;
}
public static User User
{
get
{
SessionModel sm = GetSessionModel();
if (sm.User == null && HttpContext.Current.User.Identity.IsAuthenticated)
{
sm.User = new UserService().GetUserInfo(HttpContext.Current.User.Identity.Name);
HttpContext.Current.Session[SessionKey] = sm;
}
return sm.User;
}
}
public static UserLoginInfo UserLoginInfo
{
get
{
SessionModel sm = GetSessionModel();
if (sm.UserLoginInfo == null && HttpContext.Current.User.Identity.IsAuthenticated)
{
sm.UserLoginInfo = new UserService().GetUserLoginInfo(HttpContext.Current.User.Identity.Name);
HttpContext.Current.Session[SessionKey] = sm;
}
return sm.UserLoginInfo;
}
}
}
2) 在SessionModel中存储了当前登录用户所参与的课题、在课题中所扮演的角色以及在课题中所有权限等信息。
当前账户登录时,获取到相应信息,写入SessionModel。
var userLoginInfo = new UserLoginInfo();
if (string.IsNullOrWhiteSpace(_authentication.CheckLogin(name.Trim(), password.Trim(), ref userLoginInfo)))
{
_authentication.SignIn(userLoginInfo.UserId, false);
sm.UserLoginInfo = userLoginInfo;
……
}
3) 在Global.asax里面的Application_Start方法加入代码为Model绑定集合加入上面自定义的SessionModelBinder类。
ModelBinders.Binders.Add(typeof(SessionModel), new SessionModelBinder());
4) Controller中的Action,凡是需要获取当前登录用户信息,只要在参数中加入“SessionModel sm“即可,
运行时会从Session里面取key为SessionModel的对象。
public ActionResult UserMange(SessionModel sm, int pageIndex = 1, int pageSize = 10)
{
//登录检查
if (sm.User == null)
{
string returnUrl = Url.Action("logon", "Account");
return Redirect(returnUrl);
}
……
}
5) 使用扩展:可以将需要的信息,都存储在SessionModel中
6) 个人评价:action与session没那么紧密;session数据取值在一处操作即可,代码冗余少