HttpContext is NULL when running web app in IIS

安稳与你 提交于 2020-07-28 20:30:13

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/59538132/httpcontext-is-null-when-running-web-app-in-iis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!