在MVC应用程序中第一次请求时,会话变为空

时间:2016-09-28 04:29:33

标签: c# asp.net asp.net-mvc asp.net-mvc-4 session

我有一个Silverlight application从我导航到我的MVC Application。问题是我第一次导航到我的MVC applicationSession到期。但对于后续请求,Session完全正常。在调试时,我发现在第一次请求时会发生以下流程:

调用

Application_Start (Global.asax),然后调用OnActionExecuting,设置所有会话,然后调用Application_End (Global.asax)。因此,对于下一个即时请求,Sessions变为null

Global.asax中

    protected void Application_Start()
    {
        // Register the default hubs route: ~/signalr
        RouteTable.Routes.MapHubs();

        AreaRegistration.RegisterAllAreas();
        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);

        //Start SqlDependency with application initialization
        SqlDependency.Start(connString);
    }

    protected void Application_End(object sender, EventArgs e)
    {
        //Stop SQL dependency
        SqlDependency.Stop(connString);
    }

FilterConfig.cs

 public static void RegisterGlobalFilters(GlobalFilterCollection filters)
 {
     filters.Add(new HandleErrorAttribute());
 }

OnActionExecuting Function

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
        RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
        redirectTargetDictionary.Add("action", "SessionExpire");
        redirectTargetDictionary.Add("controller", "Home");
        redirectTargetDictionary.Add("area", "");
        if (!(string.IsNullOrEmpty(Convert.ToString(HttpContext.Current.Session["SID"]))))
        {
            sessionId = Convert.ToString(HttpContext.Current.Session["SID"]);
            HttpContext.Current.Session["SID"] = sessionId;
        }
        else if (!(string.IsNullOrEmpty(Convert.ToString(HttpContext.Current.Request.QueryString["SID"]))))
        {
            sessionId = Convert.ToString(HttpContext.Current.Request.QueryString["SID"]);
            HttpContext.Current.Session["SID"] = sessionId;
        }
        if (string.IsNullOrEmpty(Convert.ToString(HttpContext.CurrentSession["SID"])))
        {
           filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
        }
    return;
}

我的代码有问题吗?任何帮助表示赞赏。

0 个答案:

没有答案