Fix MVC 5 Concurrent AJAX Tests Sharing One Cookie Container

Two simulated users pass tests individually but fail when their requests run together with a shared test client.

Applies to ASP.NET MVC 5 on .NET Framework. Use a staging or development copy to reproduce the behavior and inspect the actual response before changing production.

Diagnostic flowchart

Do the tests share an HTTP handler or cookie container? Yes: Isolate each test identity. No: Check other global test fixtures. Then run the regression checks.

Isolate the cause

Do the tests share an HTTP handler or cookie container?

  • Yes. Cookies carry authenticated session state. A shared handler can cause one virtual user’s identity to replace another’s.
  • No. A static repository, tenant ID or mutable authentication stub can also mix states when run concurrently.

Apply the fix

Give each virtual user a dedicated handler and cookie container and dispose them with the fixture. Keep test credentials and endpoints specific to the staging environment.

using (var handler = new HttpClientHandler { CookieContainer = new CookieContainer() })
using (var client = new HttpClient(handler)) {
    await ExerciseUserScenario(client);
}

Verify the result

  • Expected path. Run two distinct test identities concurrently and verify each sees only its expected fixture values.
  • Regression check. Repeat using independent setup and teardown to catch order-dependent state leakage.

Microsoft reference for testing and lifecycle · ASP.NET PB Tutorial Index

Comments