首先需要注册:
在Global中重写Init方法来指定会话需要支持的类型
public override void Init()
{
PostAuthenticateRequest += MvcApplication_PostAuthenticateRequest;
base.Init();
}
void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
HttpContext.Current.SetSessionStateBehavior(
SessionStateBehavior.Required);
}
或者
public override void Init()
{
this.PostAuthenticateRequest += (sender, e) => HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
base.Init();
}
这样才不会出现 错误System.Web.HttpContext.Current.Session 为空null
然后就是在 控制器内可以使用赋值(object)方式:System.Web.HttpContext.Current.Session["LastTime"] = DateTime.Now;
读取的方法同样可以:
DateTime TimeGet = (DateTime)System.Web.HttpContext.Current.Session["LastTime"];
换算即可。