使用SessionStateBehavior.ReadOnly写入会话变量 [英] Writing to a session variable with SessionStateBehavior.ReadOnly

查看:1224
本文介绍了使用SessionStateBehavior.ReadOnly写入会话变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的ASP.NET MVC 5应用程序中,我正在对需要读取存储在会话中的值的控制器内的方法执行 GET 请求。为了避免会话状态锁定问题,我在类级别将 SessionStateBehavior 设置为 ReadOnly

In my ASP.NET MVC 5 application, I'm performing a GET request on a method inside a controller that needs to read a value stored in session. To avoid session state locking issue, I've set SessionStateBehavior to ReadOnly on the class level.

 [SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]
    public class TestController: Controller
    {
         var test = Session["KEY"];
...

然而,偶尔,我需要覆盖会话变量到同一方法内的其他内容。 ASP.NET MVC不允许我这样做, SessionStateBehavior 设置为 ReadOnly 。我无法将其设置为必需,因为我再次遇到会话状态锁定问题,阻止了并发的AJAX请求。

However, very occasionally, I need to overwrite the Session variable to something else inside that same method. ASP.NET MVC does not allow me to do this with SessionStateBehavior set to ReadOnly. I can't set it to Required because then I run into the issue of session state locking issue again, preventing concurrent AJAX requests.

对此有什么好的解决方案?

What's a good solution for this?

编辑:我们正在使用SQL服务器进行会话状态管理。

We're using SQL server for session state management.

推荐答案

如果你的目标是.NET Framework 4.6.2并且你在SQL Server上,你可以利用新的 async SessionState module 以异步方式访问会话存储提供程序。

If you target .NET Framework 4.6.2 and you're on SQL Server, you could leverage the new async SessionState module to access the session storage providers asynchronously.

下载并安装SessionStateModule和 SqlSessionState NuGet包。

Download and install the SessionStateModule and the SqlSessionState NuGet packages.

还要考虑 SQLServer模式将会话状态存储在SQL Server数据库中。

Consider also that SQLServer mode stores session state in the SQL Server database.

注意(来自评论)

虽然ASP.NET Core中的会话是非锁定的,但只有下一版本的 SqlSessionStateProviderAsync 才会引入此功能,根据这个 msdn博客

While the session in ASP.NET Core is non-locking, only next release of SqlSessionStateProviderAsync should introduce this feature, according to this msdn blog.

另一个不同的选择是使用 StackExchange.Redis :例如对于Azure App Service中的Web应用程序,请遵循以下配置步骤
更一般地说,在Redis服务器或服务器中, RedisSessionProvider 永远不会锁定会话

Another, different option would be to use StackExchange.Redis: e.g. for a web app in Azure App Service, follow these configuration steps. More generally, in a Redis server or servers, RedisSessionProvider never locks the Session

这篇关于使用SessionStateBehavior.ReadOnly写入会话变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆