代码之家  ›  专栏  ›  技术社区  ›  dinotom

在中使用会话。Net Core 2.0

  •  2
  • dinotom  · 技术社区  · 7 年前

    在该应用程序中,我有一个基本控制器类,其主要任务是确保布局模型中包含用户的配置文件对象。

     protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (User.Identity.IsAuthenticated && Session["LayoutViewModel"] == null)
            {
                var lvm = new LayoutViewModel { AppUserId = User.Identity.GetUserId() };
                lvm.LoggedInUserProfile =
                    Services.UserService.UserHelpers.GetCompleteProfileForLoggedInUser(lvm.AppUserId);
    
                if (lvm.LoggedInUserProfile != null)
                {
                    Session["LayoutViewModel"] = lvm;
                }
                else
                {
                    Session["LayoutViewModel"] = null;
                }
            }
            base.OnActionExecuted(filterContext);
        }
    

    1 回复  |  直到 7 年前
        1
  •  6
  •   Ricardo Peres    7 年前

    您需要添加Microsoft。AspNetCore。Session Nuget包并在中注册会话服务 ConfigureServices

    services.AddSession(options =>
    {
        options.IdleTimeout = TimeSpan.FromSeconds(10);
        options.Cookie.HttpOnly = true;
    });
    

    在此之后,您将能够访问 HttpContext.Session 所有物