11
votes

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();
3
hello ... are you still working on this tracking solution ... do you mind sharing its code?Jalal El-Shaer
@jalchr I don't mind but the NDA would ;( I will kindly help/point in right direction if you have any questions.Matija Grcic
tip: for user tracking you need to make sure SignalR connects immediately before the page has fully loaded all resources : waitForPageLoad so make sure you set that : stackoverflow.com/questions/32856436/…Simon_Weaver

3 Answers

5
votes

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

4
votes

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

1
votes

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