Get full URL inside SignalR hub

感情迁移 提交于 2020-01-02 01:43:05

问题


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();

回答1:


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




回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/13193606/get-full-url-inside-signalr-hub

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!