【问题标题】:Using Session in .Net Core 2.0在 .Net Core 2.0 中使用会话
【发布时间】:2017-09-20 14:38:11
【问题描述】:

我正在将一个较旧的小型 mvc5 应用程序移植到 .Net Core 2.0 和 MVC 6,更多的是作为学习如何做的练习。

在那个应用程序中,我有一个 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);
    }

我知道在 UserManager 中获取 UserId 的新方法,但我无法弄清楚如何设置 Session 变量,如果这在 .Net Core 2.0 中是可行的

【问题讨论】:

标签: c# .net model-view-controller


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2018-06-30
    • 2018-09-18
    • 1970-01-01
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    • 2018-09-16
    • 1970-01-01
    相关资源
    最近更新 更多