dotnet / aspnetcore

ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.
https://asp.net
MIT License
35.38k stars 10k forks source link

Potential regression in IHttpContextAccessor injection #39093

Closed NinjaCross closed 2 years ago

NinjaCross commented 2 years ago

Is there an existing issue for this?

Describe the bug

It seems that recently:

  1. the behaviour of the injection/availabilty of IHttpContextAccessor into the Hub.OnConnectedAsync method changed
  2. the injection behaviour is not the same among different OS/Platforms.

Unfortunately I'm not able to pinpoint the exact version of SignalR CORE when the behaviour changed, since our project targets NuGet packages through floating versions, and the problem has been signaled only yesterday.

Take this code as an example of the rountrip. Let's ignore the fact that I'm starting with a HttpContext, to optain another HttpContext... it's just to explain the roundtrip taken by mi inner logics and injections

This still works everywere, and always worked before:

var newHttpContext = Context.GetHttpContext().  // called in OnConnectedAsync

/* here newHttpContext  is NOT NULL */

This worked everywere, but now just works into our Windows 10 development machines, and do not work into our Windows 2019 servers

 // called by OnConnectedAsync
var httpContext1 = Context.GetHttpContext();

 // we obtain a service provider contextualized into OnConnectedAsync, in order to get the injected scoped services 
var serviceProvider = httpContext1.RequestServices.GetRequiredService<IServiceProvider>();

// the accessor is correctly resolved, but...
var accessor = serviceProvider.GetRequiredService<IHttpContextAccessor>();
var httpContext2 = accessor.HttpContext; // the http context is NULL !!!

So, when in OnConnectedAsync I use IServiceProvider to get a scoped service, and that scoped service tries to access IHttpContextAccessor.HttpContext (through constructor injection), the HttpContext is NULL.

Expected Behavior

The HttpContext returned by IHttpContextAccessor in Hub.OnConnectedAsync or any call stack started from there, should be not null and identical to the HttpContext returned by Context.GetHttpContext()

Steps To Reproduce

  1. Create a Hub
  2. Create a Scoped Service "S1", having IHttpContextAccessor as a constructor dependency
  3. Try to resolve the Scoped Service "S1" into the Hub.OnConnectedAsync
  4. The Scoped Service "S1" will have a valid IHttpContextAccessor, but the HttpContext will be null. As I said, we are experiencing the problem only on Windows Server, and NOT on Windows 10

Exceptions (if any)

No response

.NET Version

Insalled 6.0.100

Anything else?

No response

NinjaCross commented 2 years ago

Sorry, this issue has been created by mistake and I closed it. The correct issue is #39095 Delete this at your will.