Search code examples
c#asp.netsignalr

Set cookie from SignalR hub on the server


Is there anyway I can set a cookie from inside a SignalR hub, specifically the OnConnected method. I want to send a cookie with a session id.

I tried this but it didn't seem to work, it also looks awkward because I'm not sure why I need to provide a key value pair of a string and a cookie.

public override Task OnConnected()
{
    var guid = new Guid();
    Context.RequestCookies.Add("SessionID", new Microsoft.AspNet.SignalR.Cookie("SessionID", guid.ToString()));
    return null;
}

Solution

  • This is an old question, but in case anyone stumbles on it, there's a way to add cookies from a hub in signalr 2.0+. The HttpContextBase can be accessed through hub request context, so you can do something like this:

    var newCookie = new HttpCookie("cookieName", "cookieValue");
    Context.Request.GetHttpContext().Response.Cookies.Add(newCookie);