C# 在.NETCore2.0中使用会话

C# 在.NETCore2.0中使用会话,c#,.net,model-view-controller,C#,.net,Model View Controller,我正在将一个旧的小型mvc5应用程序移植到.NETCore2.0和MVC6,更多的是作为一个练习来学习如何做 在该应用程序中,我有一个基本控制器类,其主要任务是确保布局模型中包含用户的概要文件对象 protected override void OnActionExecuted(ActionExecutedContext filterContext) { if (User.Identity.IsAuthenticated && Session["Layo

我正在将一个旧的小型mvc5应用程序移植到.NETCore2.0和MVC6,更多的是作为一个练习来学习如何做

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

 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);
    }

我知道UserManager中有一种获取用户ID的新方法,但我很难确定如何设置会话变量,如果这在.Net Core 2.0中是可行的,那么您需要添加Microsoft.AspNetCore.Session Nuget包,并在
ConfigureServices
中注册会话服务:

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

在此之后,您将能够访问
HttpContext.Session
属性。

使用Microsoft.AspNetCore.Session