dotnet / dotnet/aspnetcore

Replace task.Wait() with Await disposes HttpContext.Features of the current HttpRequest

Open
#64,507 11 comments 0 reactions 0 assignees View on GitHub
area-networking
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

Hi,

I have a crazy problem I don't really understand.

Background: Old web application, developed Net.Framework.1.1, startet 2006 2.0, later 4.0, two years 8.0, now 10.0, IIS In-Process hosted, Minimal Api.

The application uses 4 additional services, one is like a session service (replaced the Framework ASP NET State Service), one is something like a cache (but with Db-Checks), one creates pdf files, the latest is a routing calculation. (2)/(3) earlier with NET.Remoting. Now all 4 services are IIS In-Process hosted, Minimal Api, they consume a Xml-Document with the command and parameters and send a Xml-Document back. The client-code executed by the web application and the first part of the server-code of all 4 services is nearly the same, that calls the (sometimes 15 - 20 years old) functions.

Long time I didn't use async / await. Started the last years with the switch to NET.8. Later I found:

```
_task = _httpClient.PostAsync(...)
_task.Wait()
```

is bad, because it blocks the current thread. So I've started to recheck the whole code to find such **.Wait(** and to add **async** on the whole function stack.

But: Changed that row to

```
Using _httpResponseMessage As System.Net.Http.HttpResponseMessage = Await _httpClient.PostAsync(...)
```

results in an error later:

```
IFeatureCollection has been disposed.
Object name: 'Collection'.
at Microsoft.AspNetCore.Http.Features.FeatureReferences`1.ThrowContextDisposed()
at Microsoft.AspNetCore.Http.Features.FeatureReferences`1.ContextDisposed()
at Microsoft.AspNetCore.Http.Features.FeatureReferences`1.Fetch[TFeature](TFeature& cached, Func`2 factory)
at Microsoft.AspNetCore.Http.DefaultHttpRequest.get_Cookies()
```

trying to read the number of cookies of the request. Rechecked the code, no missing Await found. The error happens in the client of the session service, trying to read the session. If the browser doesn't send a cookie, no crash.

Looks like using Await changes the thread and removes handles to HttpContext-Objects, so these objects are disposed.

But normally different calls of the same function should not affect the life span of other objects.

Additional observation: If I add a private variable this_CookieCollection to my main class and initialize it with HttpRequest.Cookies, that crash can be removed. But then follows the next crash with HttpRequest.QueryString and the same type of error message. It's not possible to fix that bug using the same idea.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.