问题
My code in SignalR hub:
public class AlertHub : Hub
{
public static readonly System.Timers.Timer _Timer = new System.Timers.Timer();
static AlertHub()
{
_Timer.Interval = 60000;
_Timer.Elapsed += TimerElapsed;
_Timer.Start();
}
static void TimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//Random rnd = new Random();
//int i = rnd.Next(0,2);
Alert alert = new Alert();
i = alert.CheckForNewAlerts(EmpId);
var hub = GlobalHost.ConnectionManager.GetHubContext("AlertHub");
hub.Clients.All.Alert(i);
}
}
Somehow I need to pass EmpId parameter. How to accomplish this?
Some more client details: On my aspx page I have the following code:
<script type="text/javascript">
$(function () {
var alert = $.connection.alertHub;
alert.client.Alert = function (msg) {
if (msg == 1) {
$("#HyperLink1").show();
$("#HyperLink2").hide();
}
else {
$("#HyperLink1").hide();
$("#HyperLink2").show();
}
//$("#logUl").append("<li>" + msg + "</li>");
};
$.connection.hub.start();
});
</script>
On ASPX page, my EmpID is in the session object and I need to somehow use it in the SignalR hub.
回答1:
You can keep track of connected users (and any associated metadata) by connection (check here and here for examples) and on your timer tick check your stored local data for whatever you need.
By itself, signalR won't pass you anything. The client has to pass things along.
If your client has the employee ID, have it send it to the signalr hub on connect. You can add a handler know when the client connects in your aspx page javascript, and then send it to the hub. The hub can then keep track of ConnectionId, EmployeeID
in a dictionary and you can use that to access back on the particular client or do whatever you want.
Check the links I posted, they show how to do this.
回答2:
In addition to the accepted answer I have used this to pass multiple query strings from client to hub: In Client:
Dictionary<string, string> queryString = new Dictionary<string, string>();
queryString.Add("key1", "value1");
queryString.Add("key2", "value2");
hubConnection = new HubConnection("http://localhost:49493/signalr/hubs", queryString);
---Rest of the code--------
In Hub class:
public override Task OnConnected()
{
var value1 = Convert.ToString(Context.QueryString["key1"]);
var value2 = Convert.ToString(Context.QueryString["key2"]);
return base.OnConnected();
}
I am using the “Microsoft.AspNet.SignalR.Client” library of version “2.3.0.0” in a windows form application using c#.
来源:https://stackoverflow.com/questions/22183176/how-to-pass-a-parameter-to-hub-in-signalr