15

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?

Vivendi
  • 20,047
  • 25
  • 121
  • 196
  • 3
    This happened to me too on two occasions. Not sure if they apply to you, but maybe it proofs helpful. First, make sure you turn on WebSockets on the IIS. Second, if your app uses app.UseAuthentication - which most likely it is - then make sure it's in the right order as Microsoft describes it [here](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.1#middleware-order). – Dennis VW Dec 31 '19 at 01:43
  • 2
    @Dennis1679 I enabled WebSockets on IIS and that seemed to do the trick! Thanks a lot for that suggestion! Could you please provice this as an answer so I have something to accept? – Vivendi Dec 31 '19 at 11:04

2 Answers2

35

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.

Community
  • 1
  • 1
Dennis VW
  • 2,977
  • 1
  • 15
  • 36
  • 1
    At the time of writing the setting you need is in the App Service (not the plan) under: Settings > Configuration > General settings > Platform settings > Web sockets. P.S. you saved me! – Ben Oct 13 '21 at 14:39
0

To enable websockets in azure app service. Open app service in azure portal -> configuration -> general settings -> websockets on or off. Described here