如何解决为什么有时在.net core mvc应用程序中我的会话值会丢失?
我在应用程序(asp.net core mvc)中遇到了一个深层次的问题。直到我进入Asp.net mvc,我才从未发生过这种问题。
会话工作正常,当我在Visual Studio中使用断点检查会话的值时,会话的每个值都会保留。但是,如果我删除断点并仅运行我的应用程序,则会话值将为空/空,并且此问题是间歇性的。我可以认为这是.net core mvc中的一个大缺陷/错误。
我在Session variable value is getting null in ASP.NET Core和Session Lost in Asp.net Core application中检查了很少的答案,但没有一个对我有用。
我在startup.cs中有这些设置
public void Configure(IApplicationBuilder app,IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseAuthentication();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areas",template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "default",template: "{controller=Home}/{action=Index}/{id?}");
});
}
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromDays(1);
});
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
}).AddCookie("Cookies",options =>
{
// Configure the client application to use sliding sessions
options.SlidingExpiration = true;
// Expire the session of 15 minutes of inactivity
options.ExpireTimeSpan = TimeSpan.FromDays(1);
if (appSettings.RedisCachingEnabled)
{
options.EventsType = typeof(CustomCookieAuthenticationEvents);
}
options.Cookie.HttpOnly = true;
})
我现在坚持为该项目进行构建,因为最初的会议运行良好。最后,我正在设置并进行这样的会话
UserController.cs类
public IActionResult SetUsers(int id) {
_sessionData.users= some api call that get users;
return RedirectToAction("LoadUsers","Home",new
{
area = "Admin",});
}
管理区域/ homeController.cs
public IActionResult LoadUsers() {
var users = _sessionData.users; // some users are lost when trying to get users from session
// some time its completely null. But if applied breakpoint,it shows correct session
}
这是我的会话课程
public class SessionData : ISessionData
{
public IHttpContextAccessor _httpContextAccessor;
public SessionData(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public List<User> users
{
get
{
var users= _httpContextAccessor.HttpContext.Session.GetObjectFromJson<List<User>>("users");
if (users == null)
{
users = new List<User>();
}
return users;
}
set
{
_httpContextAccessor.HttpContext.Session.SetObjectAsJson("users",value);
}
}
}
解决方法
您可以为IHttpContextAccessor创建自己的扩展方法,以保存json数据或在会话中检索它。 这是一个例子
Type 'ObjectSchema<object & { boolOrString: BooleanSchema<boolean> | StringSchema<string>; }>' is not assignable to type 'ObjectSchema<{ boolOrString: string | boolean; }>'.
The types of 'fields.boolOrString' are incompatible between these types.
Type 'Schema<BooleanSchema<boolean> | StringSchema<string>>' is not assignable to type 'Schema<string | boolean>'.
Type 'BooleanSchema<boolean> | StringSchema<string>' is not assignable to type 'string | boolean'.
Type 'BooleanSchema<boolean>' is not assignable to type 'string | boolean'.
Type 'BooleanSchema<boolean>' is not assignable to type 'string'.
并在您的控制器中,将IHttpContextAccessor实例注入构造函数中,您应该能够检索对象并将其保存到会话中
public static class Session
{
private static IHttpContextAccessor _httpContextAccessor;
private static ISession _session;
public static void Initialized(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
_session = _httpContextAccessor.HttpContext.Session;
}
public static bool SetObject(this IHttpContextAccessor httpContextAccessor,string key,object value)
{
bool status = false;
try
{
Initialized(httpContextAccessor);
_session.SetString(key,JsonConvert.SerializeObject(value));
status = true;
}
catch (Exception ex)
{
}
return status;
}
public static T GetObject<T>(this IHttpContextAccessor httpContextAccessor,string key)
{
try
{
Initialized(httpContextAccessor);
var value = _session.GetString(key);
return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
}
catch (Exception ex)
{
return default(T);
}
}
}
用户信息类:
public class SessionController : Controller
{
private readonly UserInfo _user;
public SessionController (IHttpContextAccessor iHttpContextAccessor)
{
_user = iHttpContextAccessor.GetObject<UserInfo>("user");//get session with
//key user
}
public IActionResult Login(LoginModel User)
{
UserInfo userInfo = new UserInfo
{
Name = "name",Id = 1
};
_iHttpContextAccessor.SetObject("user",userInfo);//set
//userinfo class into session
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。