Skip to content

Commit 1b99352

Browse files
authored
Don't re-use DefaultHttpContext if IHttpContextAccessor is in use (#15049) (#20844)
* Don't re-use DefaultHttpContext if IHttpContextAccessor is in use - Consumers may still get null or an ODE but will never end up with data from a different request. - Make sure an ODE is thrown from all properties on HttpContext after the request is over.
1 parent 5353ce9 commit 1b99352

File tree

5 files changed

+609
-463
lines changed

5 files changed

+609
-463
lines changed

src/Hosting/Hosting/src/Http/DefaultHttpContextFactory.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ public DefaultHttpContextFactory(IServiceProvider serviceProvider)
2626
_serviceScopeFactory = serviceProvider.GetRequiredService<IServiceScopeFactory>();
2727
}
2828

29+
internal IHttpContextAccessor HttpContextAccessor => _httpContextAccessor;
30+
2931
public HttpContext Create(IFeatureCollection featureCollection)
3032
{
3133
if (featureCollection is null)

src/Hosting/Hosting/src/Internal/HostingApplication.cs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,14 @@ public void DisposeContext(Context context, Exception exception)
9696
if (_defaultHttpContextFactory != null)
9797
{
9898
_defaultHttpContextFactory.Dispose((DefaultHttpContext)httpContext);
99+
100+
if (_defaultHttpContextFactory.HttpContextAccessor != null)
101+
{
102+
// Clear the HttpContext if the accessor was used. It's likely that the lifetime extends
103+
// past the end of the http request and we want to avoid changing the reference from under
104+
// consumers.
105+
context.HttpContext = null;
106+
}
99107
}
100108
else
101109
{

0 commit comments

Comments
 (0)