Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get full URL inside SignalR hub

I'm developing an user tracking solution using SignalR, as a fun project to learn SignalR, for ASP.NET MVC applications.

Currently i can track logged users and how long are they on a specific page. If they move to another page i track that also and the timer that SignalR is updating resets... Many other features are implemented or partially implemented.

The problem i'm facing is how to get the full url Controller/Action/Parameters inside SignalR hub?

When i use HttpContext.Current.Request.Url the url is always /signalr/connect.

NOTE:

var hub = $.connection.myHub;
$.connection.hub.start();

is in the _Layout.cshtml.

UPDATE:

I've tried to use

var location = '@HttpContext.Current.Request.Url';
var hub = $.connection.myHub;
$.connection.hub.start().done(function () {
    hub.setLocation(location);
});

And the location is passed correctly but I need it on the Connect() task not later. Is it possible to do this?

UPDATE 2:

This approach doesn't work

var hub = $.connection.myHub;
$.connection.hub.start(function(){hub.setLocation(location)});

as the Connect() is called before.

In my hub i have several methods but i would like pass a value (in my case a location) to the Connect(), is that possible?

public class MyHub : Hub, IDisconnect, IConnected
{  
    public Task Connect()
    {
       //do stuff here
       //and i would like to have the **location** value
    } 

    public Task Disconnect()
    {
       //do stuff here            
    }             
}

Update 3

Use QueryString to pass data before the Connect() occurs.

var location = '@HttpContext.Current.Request.Url';

var hub = $.connection.myHub;
$.connection.hub.qs = "location= + location;
$.connection.hub.start();
like image 980
Matija Grcic Avatar asked Nov 02 '12 10:11

Matija Grcic


3 Answers

Passing data like your location value to Connect() is possible via a querystring parameter: SignalR: How to send data to IConnected.Connect()

like image 114
Alexander Köplinger Avatar answered Nov 15 '22 14:11

Alexander Köplinger


Using query-string is not very secure, cause a hacker can forge JS code and send you wrong location breaking whatever logic you have behind it.

You can try to get this from owin-enviromment variables

var underlyingHttpContext = Context.Request.Environment[typeof(HttpContextBase).FullName] as HttpContextBase;

Then extract whatever you need.

It will work on IIS, for non-IIS hosting look for other OWIN stuff https://github.com/aspnet/AspNetKatana/wiki/OWIN-Keys

like image 36
Alex from Jitbit Avatar answered Nov 15 '22 16:11

Alex from Jitbit


You could pass it from your client js call to your hub as a parameter.

like image 1
dove Avatar answered Nov 15 '22 15:11

dove