How to pass some data through signalR header or query string in .net core 2.0 app

Arash picture Arash · Sep 18, 2017 · Viewed 8.7k times · Source

Using signalR in .net 4.7 we were able to pass two variables from the client application to signalR server. Here is the code snippet:

public class MyHub : Hub
{
    protected (string myVar1, string myVar2) GetValues() =>
            (
            Context.QueryString["MyVariable1"] ?? string.Empty,
            Context.QueryString["MyVariable2"] ?? string.Empty,
            );
}

The javascript client would set these variables as follows:

$.connection.hub.qs = {'MyVariable1' : 'val1', 'MyVariable2' : 'val2'};

Now, we are trying to migrate to the alpha release of signalR for .net core 2.0 applications. The blocker is that we can no longer use this method to obtain myVar1 and myVar2 values. Not only QueryString is unavailable but also headers. What is the best way to overcome this situation to be able to pass variables from client app (Typescript) or even .net core app to signalR server side? Also - how do you set variables on client side?

Answer

Pawel picture Pawel · Sep 19, 2017

You can access the HttpContext in your hub like this:

var httpContext = Context.Connection.GetHttpContext();

and then use httpContext.Request.Query["MyVariable"] to get the variable value

Edit for ASPNetCore 2.1 and later

GetHttpContext() extension method is directly accessible on Context object

using Microsoft.AspNetCore.Http.Connections;
....
var httpContext = Context.GetHttpContext();