[英]Using Session in .Net Core 2.0
我正在將一個較舊的小型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中也可行
您需要添加Microsoft.AspNetCore.Session Nuget包,並在ConfigureServices
注冊會話服務:
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
});
之后,您將能夠訪問HttpContext.Session
屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.