【发布时间】:2016-08-24 20:56:03
【问题描述】:
我有一个名为 NotificationHub 的 Signalr Hub,它负责向连接的客户端发送新通知。 NotificationHub 类使用 NotificationManager 类来检索通知数据。现在,我希望能够使用会话来存储上次访问新通知的时间,但是在 NotificationManager中使用 HttpContext.Current.Session["lastRun"] 时> 我得到一个 NullReferenceException。为了更清楚,这里是两个类的一些代码:
通知中心
[HubName("notification")]
public class NotificationHub : Hub
{
private NotificationManager _manager;
private ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public NotificationManager Manager
{
get { return _manager; }
set { _manager = value; }
}
public NotificationHub()
{
_manager = NotificationManager.GetInstance(PushLatestNotifications);
}
public void PushLatestNotifications(ActivityStream stream)
{
logger.Info($"Adding {stream.TotalItems} notifications ");
Clients.Caller.addLatestNotifications(stream);
}
//.....
}
NotificationManager
public class NotificationManager
{
private static NotificationManager _manager;
private DateTime _lastRun;
private DbUpdateNotifier _updateNotifier;
private readonly INotificationService _notificationService;
private readonly Action<ActivityStream> _dispatcher;
private long _userId;
private IUnitOfWork unitOfWork;
public NotificationService NotificationService => (NotificationService)_notificationService;
public DbUpdateNotifier UpdateNotifier
{
get { return _updateNotifier; }
set { _updateNotifier = value; }
}
public static NotificationManager GetInstance(Action<ActivityStream> dispatcher)
{
return _manager ?? new NotificationManager(dispatcher);
}
private NotificationManager(Action<ActivityStream> dispatcher)
{
_userId = HttpContext.Current.User.Identity.CurrentUserId();
_updateNotifier = new DbUpdateNotifier(_userId);
_updateNotifier.NewNotification += NewNotificationHandler;
unitOfWork = new UnitOfWork();
_notificationService = new NotificationService(_userId, unitOfWork);
_dispatcher = dispatcher;
}
private void NewNotificationHandler(object sender, SqlNotificationEventArgs evt)
{
//Want to store lastRun variable in a session here
var notificationList = _notificationService.GetLatestNotifications();
_dispatcher(BuilActivityStream(notificationList));
}
//....
}
我希望能够将 lastRun 的值存储到一个会话中,以便下次有新通知到达时可以检索该会话。我怎样才能做到这一点?
编辑:
为了澄清事情,我想在会话中存储的是服务器最后一次向客户端推送新通知的时间。我可以使用此值仅获取在 lastRun 的当前值之后发生的通知,然后将 lastRun 更新为 DateTime.Now。例如:假设用户有三个新(未读)通知,然后有两个新通知到达。在这种情况下,服务器必须知道最后一次新通知推送到客户端的时间,以便它只会发送这两个新通知。
【问题讨论】:
-
private static DateTime lastRun -
如果我错了,请纠正我,但将 lastRun 更改为静态字段将使其可供单独的用户使用。但在这里,我想为每个用户存储一个会话。
-
"我希望能够存储上次访问新通知的时间" "以便下次有新通知到达时可以检索" - 这意味着您想知道“新通知”何时在全球范围内发生,而不是每个用户。你能在问题文本中澄清一下吗?
-
SignalR 被设计为“始终连接”(以简化的方式) - 所以当您收到“新通知”时,您会立即将它们发送给客户端 - 无需“最后发送/接收”。你什么时候会触发这个? (你什么时候比较当前时间和存储时间?在什么情况下等等?)听起来你在考虑控制器/动作而不是信号器。
-
只需使用 SignalR。正如您所描述的,SignalR 开箱即用地做您想做的事。 ofc 我可能会遗漏一些东西。如果您不确定,请从头开始使用 SignalR。
标签: c# asp.net asp.net-mvc session