Signalr persistent connection with query params.

2019-03-18 17:51发布

I have a persistent connection which I would like to start with some seed info using query params. Here is the override in the connection.

    protected override Task OnConnected(IRequest request, string connectionId)
    {
        //GET QUERY PARAMS HERE

        return base.OnConnected(request, connectionId);
    }

Now I have my route setup in global.asax file which looks like this.

RouteTable.Routes.MapConnection("myconnection", "/myconnection");

And the client code looks like this

var connection = $.connection('/myconnection');

connection.start()
          .done(() =>
          {
          });

Can someone tell me how I can pass query string params to this connecton so I can read them in the override as I seem to be hitting a brick wall on this.

Cheers hope someone can help,

Dave

1条回答
Fickle 薄情
2楼-- · 2019-03-18 18:51

HUBS

   var connection = $.connection('/myconnection');
    $.connection.hub.qs = "name=John"; //pass your query string

and to get it on the server

var myQS = Context.QueryString["name"];

To access your query string in javascript you could use something like

function getQueryStringValueByKey(key) {
    var url = window.location.href;
    var values = url.split(/[\?&]+/);
    for (i = 0; i < values.length; i++) {
            var value = values[i].split("=");
            if (value[0] == key) {
                return value[1];
        }
    }
} 

Call it:

var name = getQueryStringValueByKey("name");

PERSISTENT CONNECTION

//pass your query string
var connection = $.connection('/myconnection', "name=John", true);

protected override Task OnConnected(IRequest request, string connectionId)
    {
        //get the name here
        var name = request.QueryString["name"];

        return base.OnConnected(request, connectionId);
    }

Here is the source code where you can find out more: https://github.com/SignalR/SignalR/blob/master/src/Microsoft.AspNet.SignalR.Client.JS/jquery.signalR.core.js#L106

查看更多
登录 后发表回答