简体   繁体   中英

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.

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.

 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

You need to add the Microsoft.AspNetCore.Session Nuget package and register the session services in 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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