gpt4 book ai didi

ASP.NET session 状态提供程序

转载 作者:行者123 更新时间:2023-12-02 02:12:25 25 4
gpt4 key购买 nike

我们的 ASP.NET 应用程序在同一个 session 中并行发送多个 Ajax 请求。我们还在其中一些请求期间读取/写入 HttpSessionState。出于性能原因,我想要的是让所有并发请求并行执行。我得到的是它们由 ASP.NET 序列化。我尝试配置 enableSessionState="ReadOnly",但这会破坏我们的表单例份验证。

有没有办法在一个 session 中同时获得 session 状态和并发性?我是否需要使用自定义 SessionStateProvider?那里有这方面的样本吗?

PS 我不担心访问 SessionState 时的线程安全 - 我可以通过编程方式做到这一点。

最佳答案

来自 MSDN(link):

However, if two concurrent requests are made for the same session (by using the same SessionID value), the first request gets exclusive access to the session information. The second request executes only after the first request is finished.

因此,至少对于那些需要对 Session 进行写访问的 AJAX 调用,您不适合使用默认提供程序。

不确定是否可以使用自定义提供程序解决此问题。

可以通过阻止 HttpModule 中的 ASP.NET_SessionId cookie 实现那些不需要访问 session 的 AJAX 调用的并行执行>。看我的answer对此question .

编辑:为了使这个答案更加独立,我添加了一个稍微修改过的 HttpModule 版本和一些讨论(进一步向下)。以下是可用于防止 session 状态序列化 Ajax 调用的模块代码:

using System; 
using System.Web;

namespace TestModule
{
public class TestPreventCookie : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication application)
{
application.BeginRequest +=
(new EventHandler(this.Application_BeginRequest));
application.PostAcquireRequestState +=
(new EventHandler(this.Application_PostAcquireRequestState));

}
private void Application_BeginRequest(Object source, EventArgs e)
{
//prevent session cookie from reaching the service
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
if (BlockCookie(context))
{
context.Request.Cookies.Remove("ASP.NET_SessionId");
}
}
private void Application_PostAcquireRequestState(Object source, EventArgs e)
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
if (BlockCookie(context))
{
var s = context.Session;
if (s != null)
s.Abandon();
}
}
private bool BlockCookie(HttpContext context)
{
// put code here that determines if the session cookie should be blocked
// this could be based on the path of the current request for instance
// only block the cookie when you *know* that access to the Session is not needed
}
}
}

这个模块背后的想法是,根据项目要求使用一些标准,我们从当前上下文中删除 ASP.NET_SessionId cookie(注意,我们不会在客户端使它过期) .

这意味着在请求管道的更深处,服务器将创建一个新 session 。为了防止这个新创建的 session 破坏客户端上现有的 ASP.NET_SessionId cookie,我们在创建后立即放弃它。

最终结果是,每个被模块“拦截”的请求都将像没有 session 一样执行。

关于ASP.NET session 状态提供程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12176242/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com