Storing data in a Session
I have a problem when trying to store data in a Session inside a hub method.
The repository that demonstrates the issue can be found at (including instructions for running, but basically dotnet restore and dotnet run):
https://github.com/Stamo-Gochev/SignalR.Core.Sample
Steps to reproduce:
- Setup and run the project as explained in the repository.
- Type a username in the prompt.
- Type a message in the input field and click "Send".
This is calling the Send method of the hub:
public class Chat : Hub
{
public static ISession Session { get; set; }
public Chat(IHttpContextAccessor httpContextAccessor)
{
Session = httpContextAccessor.HttpContext.Session;
}
public void Send(string name, string message)
{
Session.SetString("key", DateTime.Now.ToString());
var someValue = Session.GetString("key");
//return Clients.All.InvokeAsync("Send", data);
Clients.All.SendAsync("broadcastMessage", name, "${someValue}: message");
}
}
I am getting the following server-side error:
"The session cannot be established after the response has started."
which is mentioned in the documentation:
If you try to create a new Session (that is, no session cookie has been created) after
you have already begun writing to the Response stream, the exception InvalidOperationException:
The session cannot be established after the response has started is thrown.
The exception can be found in the web server log; it will not be displayed in the browser.
What is the suggested approach for fixing this and why the Session is not properly initialized? I am able to setup an MVC example, which uses the same Session configuration and it works as expected, so I suppose that this is not the recommended way to store data in a Session when using SignalR hubs.
Additional details:
- OS - Windows 7
dotnet --version-> 2.1.300-preview1-008174- Browser - Firefox, but similar in Chrome
Session and SignalR are incompatible, the SignalR pipeline and the http request pipeline are completely decoupled. Don't use session inside of SignalR. We should document this.
/cc @rachelappel
@davidfowl Thanks. Can you suggest an alternative for managing a "cached" resource between method calls of the hub?
@Stamo-Gochev "cached" per what? There's lots of ways to do that.
@davidfowl Let's say that a user manages a list of items using "add" and "remove" hub methods. These items can be shown in two different pages of a website and they want the items to be synced between the two views. As the list of items should be shared between the different views for the same user, using a session for each user (which was possible with the old SignalR) was an applicable option.
You can store that per user state in the Context.Items on the in the hub, it'll live for as long as the connection.
@davidfowl Here is a more detailed explanation of my scenario:
There is a list of items that is the same for all users:
- when connecting for the first time, each user receives a copy of the original list of items (it never changes)
- users are anonymous - this is why I can use something like their IP address as an identificator between them
- when a user connects to the hub, they receive a copy of these items and can start adding/deleting them
- if the same user adds/deletes an item, they should be able to see these changes being synced live without reloading the same page in another tab (simplified for the explanation, this is actually a separate view)
On the other hand, any add/delete actions on the list of items should not be affecting the list of items of other users. This is why using a session in the old SignalR was applicable.
As far as I understand from the documentation though, using HttpContext.Items will not work as I am getting it in the constructor of the hub with DI:
//Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
//Chat.cs
public Chat(IHttpContextAccessor httpContextAccessor)
{
HttpContextAccessor = httpContextAccessor as HttpContextAccessor;
}
I tested this an executing a new request for add/delete calls the Chat constructor, so the context is changed. Even if it is made static just for testing purposes, the Items collection is not persisted (as stated in the docs).
I can use a Dictionary<string, List<Item>> to cache by IP as key and items as values in the hub, but I suppose there should be a different caching mechanism that I should use here?
Sorry I didn't mean to use HttpContext.Items. I meant the Context on the Hub which is has object tied to the Connection lifetime which is completely decoupled from the http context lifetime. IHttpContextAccessor should not be used in SignalR, it'll break for long polling since the request might not even be active so you could end up with a null HttpContext (cc @rachelappel some documentation gems in here 😄).
I can use a Dictionary<string, List
- > to cache by IP as key and items as values in the hub, but I suppose there should be a different caching mechanism that I should use here?
It would need to be static as the hub lifetime is per invocation (transient).
@davidfowl Thanks for the clarification. I see that Context.Items has been added in preview 2, but I was testing with preview1.
Can you clarify how the HttpContextAccessor might not be active as it is injected in the hub's constructor? I am testing this with long polling and I am not able to hit such a problem.
In addition, I see that the instance of HubConnectionContext has been removed in preview2, so what is the recommended approach to get the IP of the incoming request? It was available in the HubConnectionContext and it is also present in HttpContextAccessor.HttpContext.Connection:
//1.0.0-preview1
public class HubCallerContext
{
public HubCallerContext(HubConnectionContext connection);
public HubConnectionContext Connection { get; }
public ClaimsPrincipal User { get; }
public string ConnectionId { get; }
}
//1.0.0-preview2
public abstract class HubCallerContext
{
protected HubCallerContext();
public abstract string ConnectionId { get; }
public abstract string UserIdentifier { get; }
public abstract ClaimsPrincipal User { get; }
public abstract IDictionary<object, object> Items { get; }
public abstract IFeatureCollection Features { get; }
public abstract CancellationToken ConnectionAborted { get; }
public abstract void Abort();
}
@davidfowl Thanks for the clarification. I see that Context.Items has been added in preview 2, but I was testing with preview1.
You should use preview2.
Can you clarify how the HttpContextAccessor might not be active as it is injected in the hub's constructor? I am testing this with long polling and I am not able to hit such a problem.
You're getting lucky. The request can end while the hub is still alive, it's a built in race condition.
In addition, I see that the instance of HubConnectionContext has been removed in preview2, so what is the recommended approach to get the IP of the incoming request? It was available in the HubConnectionContext and it is also present in HttpContextAccessor.HttpContext.Connection:
https://github.com/aspnet/SignalR/issues/2093
Thanks @davidfowl. Learned a few things here.
Are Context.Items replicated across all servers when scaling out? (Even when using azure SignalR service)
Can it be used to map connections to users? This is not documented in https://docs.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/mapping-users-to-connections
Are Context.Items replicated across all servers when scaling out?
No, but you should be OK. When scaling out, you have to use Sticky Sessions (aka ARR Affinity in Azure App Service/IIS) to ensure all requests for the connection go to the same server. Azure SignalR also maintains this and will route all traffic for a connection to the same server, so Context.Items will continue to work.
Can it be used to map connections to users?
The documentation you linked is for ASP.NET SignalR, not ASP.NET Core SignalR. Unfortunately no, the Context.Items cannot be used to map connections to users. We do the mapping of Connections to Users before calling your OnConnectedAsync, so there won't be a chance for you to assign this data before we get the mapping ID.
What are you storing in Context.Items that you want to use as this mapping?