我是 .Net 核心的新手,我正在尝试管理和访问控制器类之外的会话变量。
会话变量设置正确,我可以在调试期间看到它们,但每次请求都会丢失。请建议我解决方案,或者我出了什么问题。
谢谢,
萨蒂什
下面是代码
//Statup.cs :
////Added the below two lines in the ConfigureServices() method
services.AddSession(options => {options.IdleTimeout = TimeSpan.FromMinutes(30);});
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
////Added the below two lines in the Configure() method
app.UseSession();
Sessions.Configure(app.ApplicationServices.GetRequiredService<IHttpContextAccessor>());
//Session.cs : Static class to handle session variables
using Microsoft.AspNetCore.Http;
using System;
namespace Dsms.Website.Helper
{
public static class Sessions
{
private static IHttpContextAccessor _httpContextAccessor;
public static void Configure(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public static Guid UserId
{
get { return Guid.Parse(_httpContextAccessor.HttpContext.Session.GetString("UserId")); }
set { _httpContextAccessor.HttpContext.Session.SetString("UserId", value.ToString()); }
}
}
}
//BaseController.cs:
////Constructor
public BaseController(IApplicationSettings applicationSettings, IServiceClient serviceClient, ICacheProvider cacheProvider, IHttpContextAccessor httpContextAccessor)
{
_applicationSettings = applicationSettings;
_serviceClient = serviceClient;
_cacheProvider = cacheProvider;
_httpContextAccessor = httpContextAccessor;
//===> On every request the session variable is null here and so it calls DB.
if (string.IsNullOrEmpty(Sessions.UserId))
{
GetUserDetails();
}
}
//// Method GetUserDetails()
public List<UserModel> GetUserDetails()
{
////Get user details from DB
//.
//.
//.
//// Assign value to the session variables obtained from DB
Sessions.UserId = user.UserId;
}