简体   繁体   中英

Enabling concurrent requests from same session in ASP.NET Core

EDIT: This was apparently an issue with testing in the browser, not with the code. Sessions in Core are disabled by default as they should be.

Original question:

I'm working on a web API which needs to handle multiple requests concurrently, even from the same client. It is an ASP.NET Core MVC (1.1.2) app currently targeting the full framework (4.5.2), mostly for compatibility with other libraries.

When I first tested my concurrency, I was surprised that the requests were not concurrent at all. I googled around and found out that ASP.NET does not handle requests within a session concurrently, but instead queues them. A quick test shows that sessions are likely to be the culprit:

[HttpGet("sleep")]
public string Sleep()
{
   Thread.Sleep(5000);
   return $"Done at {DateTime.Now:u}";
}

When I rapidly request this from multiple tabs in the same browser, it takes 5 seconds between each tab. This is not the case when I use multiple browsers, it responds multiple times within a 5 second window.

When searching for a solution I kept stumbling upon ways to disable session state in ASP.NET, but nothing for Core.

As far as sessions are concerned, I am using the default API project template and I have done nothing to specifically enable/setup session state.

Is there a way to get rid of session state in ASP.NET Core? Or is there a better solution to enable concurrent requests?

You already have concurrent requests enabled in ASP.NET Core, no need to modify your code. Session in ASP.NET Core is non-locking. If multiple requests modify the session, the last action will win.

As-stated in the documentation :

Session state is non-locking. If two requests simultaneously attempt to modify the contents of a session, the last request overrides the first. Session is implemented as a coherent session, which means that all the contents are stored together. When two requests seek to modify different session values, the last request may override session changes made by the first.

If you set this attribute on your controller class

[SessionState(SessionStateBehavior.ReadOnly)]

It will set the session to not lock and therefore you will be able to make concurrent requests

You can read more about it here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM