New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
HttpContext NULL issue?? System.NullReferenceException on HttpContextAccessor? Core 2.1 #3668
Comments
Realize that IHttpContextAccessor is a feature of last resort as it's easy to use incorrectly. Where does GetUserNetworkId get called from in your application? HttpContext is only valid during a request, and it should only be accessed on the main request thread. |
I have 6 controllers that implements IUserRepository like below HomeController and calls the function GetUserNetworkId()
|
HttpContext is available in HomeController, pass it directly into GetUserNetworkId rather than relying on IHttpContextAccessor. |
Or if you just want to use the |
Is passing HttpContext to a different controller or interface safe do so?? |
You can pass it anywhere you like so long as only one thread is using it at a time and they stop using it after the end of the request. |
Before the end of the request 😄 |
As this appears to be a misunderstanding of how long a context lasts for, and advice has been given, closing |
@blowdart Can I ask how long does Http Context last???? |
It lasts for the duration of the request, and can be used only from the request thread. |
Describe the bug
I am using asp.net core 2.1
Because HttpContext becomes null, I get System.NullReferenceException.
I have interface called 'IUserRepository' and it is implemented in Startup class.
Startup.cs:
Then I get user's info and tells whether the user is validated user or not.
However, I get System.NullReferenceException: Object reference not set to an instance of an object.
at Services.UserRepository.GetUserNetworkId() in ...\Services\UserRepository.cs:line 122
I marked where is the line#122 in below code.
UserRepository.cs:
The line#122 creates a class BasicAuthenticationHeader
and decodes AuthenticationHeader of the HttpConext.
I think (guess) there is where the HttpContext becomes Null out.
class BasicAuthenticationHeader.cs:
private readonly string _authenticationHeaderValue;
The more weird is that it happens at random, and I don't know why HttpContext gets lost.
Please help.
Thank you.
To Reproduce
Steps to reproduce the behavior:
The text was updated successfully, but these errors were encountered: