p.c*_*ell 7 asp.net-mvc session
考虑一个需要设置会话变量的ASP.NET MVC应用程序.它在整个应用程序中使用.它可以通过读取浏览器cookie上的散列值或者在用户登录后设置.
在WebForms + Master Page模型中,我将检查母版页的Page_Load().也许不是最终的事件,但它很容易找到.
您将如何检查并强制ASP.NET MVC中存在会话变量?考虑到这个问题可能不涉及用户登录详细信息,而是一些其他数据(可能是第一次访问时间).
解决方案尝试
public void Application_BeginRequest(Object source, EventArgs e)
{
    HttpApplication application = (HttpApplication)source;
    HttpContext context = application.Context;
    context.Session["SomeDateTime"] =  DateTime.Now.ToString();
    // results in Object reference not set to an instance of an object.
    // context.Session is null
} 
Oma*_*mar 10
你有两个选择.
1.在基本控制器的Initialize功能中放置逻辑
假设所有控制器都从基本控制器继承,您可以Execute()在基本控制器功能的覆盖中放置所需的逻辑.
public class BaseController : Controller
{
    public BaseController()
    {
    }
    protected override void Initialize(System.Web.Routing.RequestContext requestContext)
    {
            // check if the user has the value here using the requestContext.HttpContext object
    }
{
2.使用Global.asax void Application_PreRequestHandlerExecute(Object source, EventArgs e)函数
public void Application_PreRequestHandlerExecute(Object source, EventArgs e)
{
    HttpApplication application = (HttpApplication)source;
    HttpContext context = application.Context;
    // use an if statement to make sure the request is not for a static file (js/css/html etc.)
    if(context != null && context.Session != null)
    {
          // use context to work the session
    }
}
注意:第二部分适用于任何ASP.NET应用程序,WebForms或MVC.
至于enforcing他们有一个特定的会话变量,它真的非常开放.您可以重定向到某个页面,以便他们填写表单或选择一个选项.或者,如果找不到,则可能只有一个默认值设置为某个会话密钥.
编辑
在玩这个时,我发现了一个很大的问题Application_PreRequestHandlerExecute.正在为服务器发出的任何请求调用事件处理程序,无论是.css/.js/.html文件.我不确定这是我的工作站设置方式的问题,还是ASP.NET/IIS的工作原理,所以我确保在实现上述方法时不会在所有请求上调用它.
出于以前的原因,我在会话中用if声明包装了要完成的工作.