我需要在signalR中心创建组,但Context.ConnectionId行为null:
public class MetricHub : Hub
{
public MetricHub()
{
Groups.Add(Context.ConnectionId, "Syslog");
Groups.Add(Context.ConnectionId, "Heatmap");
}
}
这是使用MetricHub类的backgroundTicker类:
using AutoMapper;
using Makbin.Data;
using Makbin.Web.Model;
using Makbin.Web.ViewModels;
using Microsoft.AspNet.SignalR;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Hosting;
namespace Makbin.Web.Hubs
{
public class test
{
public int id { get; set; }
public string name { get; set; }
}
public class BackgroundTicker : IRegisteredObject
{
private readonly MakbinRepository _repository;
private Timer devicesTimer;
private IHubContext hub;
public BackgroundTicker()
{
_repository = new MakbinRepository();
HostingEnvironment.RegisterObject(this);
hub = GlobalHost.ConnectionManager.GetHubContext<MetricHub>();
devicesTimer = new Timer(OnDevicesTimerElapsed, null,
TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5));
}
private void OnDevicesTimerElapsed(object sender)
{
var result = _repository.Peripherals.Select(x => new { x.PeripheralId, x.Severity });
var finalResult = JsonConvert.SerializeObject(result, Formatting.None,
new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
hub.Clients.Group("Heatmap").broadcastMessage(DateTime.UtcNow.ToString(), finalResult);
}
public void Stop(bool immediate)
{
//deviceDetailTimer.Dispose();
devicesTimer.Dispose();
HostingEnvironment.UnregisterObject(this);
}
}
}
此代码的目的是在发送任何数据之前定义组。 在这里,我定义了两个组:Syslog,Heatmap。此外,我与客户端的连接是单向的(服务器到客户端)。
答案 0 :(得分:0)
不要忘记在Configuration
函数中映射signalR(配置身份验证后):
public void Configuration(IAppBuilder app)
{
// Enable the application to use a cookie to store information for the signed i user
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Home/Index")
});
...
app.MapSignalR();
}
开始使用signalR:
http://www.asp.net/signalr/overview/getting-started/tutorial-getting-started-with-signalr