2
votes

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

1
use Microsoft.AspNetCore.Session docs.microsoft.com/en-us/aspnet/core/fundamentals/…bitbonk

1 Answers

6
votes

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.