SignalR supporting user connection identifiers

I try to save the connection identifier for the user, I mean that even he updates the page on which he gets the same connectionid

This is what I could do so far.

javascript part

// Start the connection $.connection.hub.start(function () { chat.join(projectId, userId, userName); }).done(function () { alert("Connected!"); var myClientId = $.connection.hub.id; setCookie("srConnectionid", myClientId, 1); }); function setCookie(cName, value, exdays) { try{ var exdate = new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate); document.cookie = cName + "=" + c_value; } catch(err){ alert(err.Description); } } 

and then I created a class that inherits IConnectionIdFactory, like this

  public class MyConnectionFactory : IConnectionIdFactory { public string CreateConnectionId(IRequest request) { if (request.Cookies["srconnectionid"] != null) { return request.Cookies["srconnectionid"]; } return Guid.NewGuid().ToString(); } } 

i registered the above class in Application_start () as shown below

 protected void Application_Start() { AspNetHost.DependencyResolver.Register(typeof(IConnectionIdFactory), () => new MyConnectionFactory()); AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); } 

My problem is every time the MyConnectionFactory class is called inside the CreateConnectionId request.Cookies ["srconnectionid"] is null every time, so the user is assigned a new connectionid everytime.I can only find one link that helped me maintain connection identifiers. This is http://www.kevgriffin.com/maintaining-signalr-connectionids-across-page-instances

Can anyone suggest how to fix my problem, or is there a different approach to reusing the connection id for the same user ...?

Cookie value is set in clientide.I tried this for 2 days. It would be very helpful

Thanks in advance

+4
source share
2 answers

The cookie expiration date must be a UTC string (you don’t do this, so most likely the server is processing your expired cookie). Change your code as follows:

 var cValue = escape(value) + ((exdays==null) ? "" : "; expires=" + exdate.toUTCString()); document.cookie = cName + "=" + cValue; 

Or you can simply use the jQuery Cookie plugin to set the cookie.

UPDATE

Also, the cookie name does not match your code. You are setting a cookie called userConnectionid, but trying to access by the name 'srconnectionid'. Check for spelling errors.

+1
source

Make sure you set the path to the cookie, especially if the page is in a subdirectory. I follow a similar approach, and when the cookie path is set to root, it all works.

0
source

Source: https://habr.com/ru/post/1399199/


All Articles