Επεξεργασία

Κοινή χρήση μέσω


IHttpContextAccessor/HttpContext in ASP.NET Core SignalR

Note

This isn't the latest version of this article. For the current release, see the .NET 9 version of this article.

Important

This information relates to a pre-release product that may be substantially modified before it's commercially released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

For the current release, see the .NET 9 version of this article.

IHttpContextAccessor/HttpContext generally should be avoided with SignalR because a valid HttpContext isn't always available. In most cases, the context doesn't exist (null).

Even when an HttpContext instance is available, the context is dependent on the transport:

  • WebSockets receives a single context as the result of the initial handshake.
  • Long polling receives a new context per client "poll" request.
  • A SignalR service receives a mocked/faked/shim context.

When working within a SignalR hub, you can access the HttpContext directly using the GetHttpContextExtensions.GetHttpContext method. This method returns the HttpContext for the current connection or null if the connection isn't associated with an HTTP request. This is particularly useful for retrieving HTTP connection information, such as headers and query strings, directly within the hub. We recommend calling this method over IHttpContextAccessor for accessing HttpContext in the hub. For more information, see Use hubs in ASP.NET Core SignalR.

For guidance on IHttpContextAccessor/HttpContext in ASP.NET Core Blazor apps, see IHttpContextAccessor/HttpContext in ASP.NET Core Blazor apps.