Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 231
Arash Avatar asked Sep 18 '17 14:09

Arash


People also ask

How do I send a message to specific SignalR?

SignalR allows messages to be sent to a particular client connection, all connections associated with a specific user, as well as to named groups of connections. => await Clients. User(userId).

Is SignalR supported in .NET core?

ASP.NET Core SignalR is an open-source library that simplifies adding real-time web functionality to apps. Real-time web functionality enables server-side code to push content to clients instantly. Good candidates for SignalR: Apps that require high frequency updates from the server.

How many connections SignalR can handle?

In the default mode, the app server creates five server connections with Azure SignalR Service. The app server uses the Azure SignalR Service SDK by default. In the following performance test results, server connections are increased to 15 (or more for broadcasting and sending a message to a big group).

How do I send a message to a group in SignalR?

When user click on send button, the message to be posted to server side using signalR connection hub. Thus whenever you post any message after clicking the join group button, the message will appear to all the clients who has joined the group.


2 Answers

Late joining in this thread. The only way I could get this mechanism to work in .net core 2.2 was by:

#1 Adding two Nuget packages

<ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Http.Connections" Version="1.1.0" />
    <PackageReference Include="Microsoft.AspNetCore.Http.Features" Version="2.2.0" />
</ItemGroup>

#2 Then in our methods pe OnConnectedAsync():

    public override Task OnConnectedAsync()
    {
        var httpContext = Context.GetHttpContext();
        if (httpContext == null)
            throw new Exception("...");

        var query = httpContext.Request.Query;
        var userId = query.GetQueryParameterValue<long>("Foo");
        var clientId = query.GetQueryParameterValue<string>("Bar");
        var connectionId = Context.ConnectionId;

        [...]

        return base.OnConnectedAsync();
    }

#3 Also introduced some handy SignalR extensions:

    static public class SignalrExtensions
    {
       static public HttpContext GetHttpContext(this HubCallerContext context) =>
          context
            ?.Features
            .Select(x => x.Value as IHttpContextFeature)
            .FirstOrDefault(x => x != null)
            ?.HttpContext;

       static public T GetQueryParameterValue<T>(this IQueryCollection httpQuery, string queryParameterName) =>
          httpQuery.TryGetValue(queryParameterName, out var value) && value.Any()
            ? (T) Convert.ChangeType(value.FirstOrDefault(), typeof(T))
            : default;
    }

Hope this helps.

like image 150
XDS Avatar answered Sep 17 '22 13:09

XDS


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();
like image 25
Pawel Avatar answered Sep 17 '22 13:09

Pawel