简体   繁体   English

在.Net Core 2.0中使用会话

[英]Using Session in .Net Core 2.0

I am porting an older small mvc5 app to .Net Core 2.0 and MVC 6, more as an exercise to learn how to do it. 我正在将一个较旧的小型mvc5应用程序移植到.Net Core 2.0和MVC 6,更多地是作为练习来学习如何做。

In that app I have a Base Controller class, whose main job is to ensure the layout model has the user's profile object in it. 在该应用程序中,我有一个Base Controller类,其主要工作是确保布局模型中包含用户的配置文件对象。

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

I am aware of the new method in UserManager to get the UserId but am having trouble figuring out how to set the Session variable, if that is even doable in .Net Core 2.0 我知道UserManager中获取UserId的新方法,但是在弄清楚如何设置Session变量时遇到麻烦,即使该方法在.Net Core 2.0中也可行

You need to add the Microsoft.AspNetCore.Session Nuget package and register the session services in ConfigureServices : 您需要添加Microsoft.AspNetCore.Session Nuget包,并在ConfigureServices注册会话服务:

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

After this you will be able to access the HttpContext.Session property. 之后,您将能够访问HttpContext.Session属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM