Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

asp.net core - HttpContext is NULL when running web app in IIS

I have two application, both running on the same Windows machine. One application is IdentityServer4, and the other is my own web application (Server side Blazor app).

Both web apps are build with .NET Core 3.1.

When I navigate to my web app, I first get redirected to my IdentityServer4 app. I login, and after that I get redirected back to my web app.

The login was successful, because there are no errors in the logs of IdentitServer. Also, I see a certain claim value on my Blazor webpage. I display this claim through CascadingAuthenticationState in my Blazor page. Through that path everything works fine.

But, whenever I try to get the logged in user through HttpContext in my "code behind" files, I get a Null reference back. For example:

public UserService(IHttpContextAccessor httpContextAccessor)
{
    // HttpClient is NULL...
    var httpCtx = _httpContextAccessor.HttpClient;  
}

The strange thing is, that it all works fine when I run my application locally in Visual Studio. When I debug in Visual Studio I see that the HttpContext is set with all my user data.

But, for some reason HttpContext is NULL when I run the app from IIS.

How can I solve this issue?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If the HttpContext null-reference exception happens after deployment to Azure App Services or IIS, you might have forgotten to enable WebSockets.

Here is the deal:

If the app runs on Windows with IIS: WebSockets must be enabled.

See the IIS/IIS Express support section.

It seems that this is a prerequisite that you have to follow. I only recently discovered this myself after dealing with the same issue and deciding to publish my app to Azure from within Visual Studio. After I did so, Visual Studio gave me a nice warning telling me to enable WebSockets protocol on the Azure App Service.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...