即使使用禁用的Session,ASP.NET MVC 5并发请求也会排队

时间:2015-11-09 03:36:05

标签: asp.net-mvc multithreading concurrency asp.net-mvc-5 session-state

在考虑downvoting或告诉我“google it”之前,请仔细阅读问题。这是旧/经典问题,但旧/经典解决方案不再有效。这是在Visual Studio 2013/2015中重现的非常简单的场景:

1)使用MVC模板创建ASP.NET Web应用程序: enter image description here enter image description here

2)打开Controllers \ HomeController.cs并将属性添加到控制器和“睡眠”操作:

[SessionState( System.Web.SessionState.SessionStateBehavior.Disabled)]
public class HomeController : Controller
{
    public ActionResult Sleep(int? time)
    {
        System.Threading.Thread.Sleep(time ?? 3000);
        return Content("OK");
    }

    public ActionResult Index()
    {
...

3)打开文件:Views \ Home \ Index.cshtml并使用以下内容添加/替换内容html:

<script>
    function ReqClick() {
        var startTime = Date();

        $.ajax("/Home/Sleep")
        .success(function () {
            var log = $("#log");
            var endTime = Date();
            log.text(log.text() + "Start: " + startTime.toString() + "  === " + endTime.toString());
        });
    };
</script>

<button type="button" onclick="ReqClick();">
    Request
</button>
<div>
    <textarea id="log" style="width:640px; height:480px"></textarea>
</div>

4)运行它(如果您使用的是IIS或IIS Express或Vs Dev Server,则无关紧要) - 打开主页/索引。单击F12打开开发工具,打开网络选项卡。在主页上快速单击“请求”按钮两次。您可以看到第二个请求大约需要6秒钟:

enter image description here

enter image description here

在控制器的调试模式下,您可以看到Session为空:

enter image description here

Cookie完全为空(ASP.NET会话ID不存在) enter image description here

请让我知道我错过了什么?

将以下设置添加到web.config也无济于事:

<sessionState mode="Off"/>
<pages enableSessionState="ReadOnly"/>

2 个答案:

答案 0 :(得分:3)

我在这个问题上花了很多时间,发现上面看到的大部分信息都没有解决问题。我的并行请求总是排队,我在Internet Explorer和Firefox中看到了这一点。

我发现这篇文章与使用MVC应用程序this article

有关

这表明您可以使用已禁用[SessionState(SessionStateBehavior.Disabled)],而不是将其设置为ReadOnly。

我将执行AJAX GET调用的代码移动到自己的控制器,因为当前控制器中的其他代码通过Session使用TempData。这纠正了我的问题,我对$.get()调用已禁用会话的控制器将与$.post()并行处理到使用会话的另一个控制器。

答案 1 :(得分:3)

当我使用此属性

修饰控制器时,并发并行请求对我有用
[SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]

它比上述禁用会话状态更好,并在MVC 3中添加回来。More info here

相关问题