【问题标题】:ASP.NET MVC Session variables become null through HTML.Action ChildActionASP.NET MVC Session 变量通过 HTML.Action ChildAction 变为 null
【发布时间】:2012-12-06 19:43:31
【问题描述】:

我正在使用 ASP.NET MVC3 和 Razor 语法开发一个简单的测试网站。它有_LayoutPage.cshtml 作为主模板,它使用@HTML.Action 在每个页面的站点顶部打印用户ID。

我为这个局部视图实现了一个名为userInfochildAction,它从HTTPContext.Session 读取用户ID 并将其打印出来。子操作在一个名为CommonActionController 的控制器中实现,该控制器派生自Controller。除了用户 ID,它还从会话中读取另外两个变量并打印出来。

public class CommonActionController: Controller
{

    [ChildActionOnly]
    public ActionResult userInfo()
    {

        if(HTTPContext.Session["x-user-id"] != null)
        {
            ViewBag.UserId = (string)(HTTPContext.Session["x-user-id"]);
            ViewBag.UserFirstName = (string)(HTTPContext.Session["x-user-first-name"]);
            ViewBag.UserLastName = (string)(HTTPContext.Session["x-user-last-name"]);
            ViewBag.UserLoggedinSince = (DateTime)(HTTPContext.Session["x-user-logon-timestamp"]).ToString("f");
        }

        return PartialView();
    }
}

我的名为HomeController 的主页控制器在Dashboard 操作中实现了仪表板功能(目前它只打印“仪表板”一词)。在这个控制器中,我重写了 Controller.OnActionExecuting() 方法,该方法验证用户 ID 是否存在于会话中。就像前面提到的 childAction 一样,它从 session 中读取总共三个变量。

public class HomeController: Controller
{


    public HomeController()
    {

    }


    protected override void OnActionExecuting(ActionExecutingContext ctx)
    {


        base.OnActionExecuting(ctx);

        if(HTTPContext.Session["x-user-id"] == null)
            ctx.Result = new RedirectResult("logon/userlogon");

        if(HTTPContext.Session["x-user-logon-timestamp"] == null)
            ctx.Result = new RedirectResult("logon/userlogon");

        if(HTTPContext.Session["x-user-internal-flag"] == null)
            ctx.Result = new RedirectResult("logon/userlogon");

    }

    public ActionResult Dashboard()
    {
        // nothing to see here
        return View();
    }

}

我已经稍微清理了代码以删除 debug.print 语句。

根据日志,我看到OnActionExecuting() 方法和userInfo 子操作同时被调用。在某一时刻OnActionExecuting() 获取会话变量的空值。在日志中,我可以看到在调用ChildAction 点之前,会话变量的值保持在OnActionExecuting() 内。一旦childaction 访问它们,它们就会变为空。

当我评论从子操作访问会话的代码时,一切正常。我究竟做错了什么?访问会话变量时我必须采取一些预防措施吗?这是因为我不知道如何异步访问 Session 吗?

我的web.config也有关注:

<modules runAllManagedModulesForAllRequests="true"/>

【问题讨论】:

  • 请提供代码。
  • 附加代码。抱歉应该早点做的。

标签: asp.net asp.net-mvc-3 session


【解决方案1】:

1)开始->管理工具->服务

2) 右键单击​​ ASP.NET 状态服务并单击“开始”

*此外,您可以将服务设置为自动,以便在重新启动后运行。

更多详情可以查看我的博文:http://jamshidhashimi.com/2011/03/16/unable-to-make-the-session-state-request-to-the-session-state-server/

参考: Unable to make the session state request to the session state server

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-13
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多