Skip to content
This repository has been archived by the owner on Nov 20, 2018. It is now read-only.

HttpContextAccessor behaves differently under .NETStandard1.3 vs .NET 4.5.1 #723

Closed
dotnetjunkie opened this issue Oct 9, 2016 · 5 comments
Assignees

Comments

@dotnetjunkie
Copy link

The HttpContextAccessor class (see here) implementation contains a compiler directive that contains a different implementation for .NETStandard1.3. The .NET 4.5.1 implementation uses CallContext, while the .NETStandard1.3 version uses AsyncLocal<T> under the covers.

These two versions however behave differently. While the .NET 4.5.1 version of HttpContextAccessor is stateless, the .NETStandard version contains state in the form o an instance field. This could potentially cause a system, when deployed under .NET 4.5.1, to run fine, while completely breaking when running under .NETStandard1.3.

This will happen when an application, or third party library creates its own instance of the HttpContextAccessor. While the stateless .NET 4.5.1 version will always request the HttpContext from the CallContext, the .NETStandard version will create a new async-local container per class instance. This will cause ASP.NET Core to set the HttpContext in a different bucket then where the the application or 3rd party library will read from (since it contains its own AsyncLocal<HttpContext> instance).

This will obviously cause bugs that are really hard to track down.

The solution is to change the instance field to a class field:

static readonly AsyncLocal<HttpContext> _httpContextCurrent = new AsyncLocal<HttpContext>();
@davidfowl
Copy link
Member

Thats a good find. What were you doing that raised this problem?

@dotnetjunkie
Copy link
Author

I was looking at the configuration for a .NET Core application of a Simple Injector user. He actually registered that Accessor as singleton where Simple Injector created that instance. This made me trigger looking at the source code of the Accessor where I spotted this bug.

@muratg muratg added this to the 2.0.0 milestone Nov 21, 2016
@tobiasbunyan
Copy link

ActionContextAccessor seems to have the same issue. I presumed this was intentional and spent most of yesterday working round it :\ New bug report required?

@davidfowl
Copy link
Member

We'll fix this in the next release but the issue is pretty easy to avoid.

@Tratcher
Copy link
Member

Tratcher commented Dec 8, 2016

Yes please file a matching bug in MVC.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

5 participants