How to pass some data through signalR header or query string in .net core 2.0 app
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();
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 handly 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.