SignalR:为特殊用户发送消息

时间:2015-02-26 06:08:45

标签: javascript asp.net-mvc-4 model-view-controller signalr

我有一个模型,我想在添加我的模型的新项目时为特殊用户发送消息。

我添加了一个集线器。

public class VisitHub: Hub
{
    public void Update(string user, VisitNotification visit)
    {
        Clients.User(user).update(visit);
    }
}

public class VisitNotification
{
    public string Referred { get; set; }
    public string VisitType { get; set; }
    public int ReferredId { get; set; }
    public DateTime VisitedDate { get; set; }
}

并在Controller中,当我添加项目时。

var visitHub = GlobalHost.ConnectionManager.GetHubContext<VisitHub>();
visitHub.Clients.User(user.UserName).update(new VisitNotification() { Referred = reff.Name + " " + reff.Family, ReferredId = model.ReferredId, VisitType =type.Title, VisitedDate = visit.VisitDate });
                }

并在javascript中。

function Visit(data, hub) {
var self = this;
self.hub = hub;
data = data || {};
self.Referred = data.Referred || "";
self.ReferredId = data.Referred || 0;
self.VisitType = data.VisitType || "";
self.VisitedDate = getTimeAgo(data.VisitedDate);
}

function viewModel() {
var self = this;
self.newVisit = ko.observable();
self.error = ko.observable();

//SignalR related
self.newVisits = ko.observableArray();
// Reference the proxy for the hub.  
self.hub = $.connection.VisitHub;

self.loadNewVisits = function () {
    self.visits(self.newVisit().concat(self.visits()));
    self.newPosts([]);
}

//functions called by the Hub
self.hub.client.loadVisits = function (data) {
    var mappedVisits = $.map(data, function (item) { return new Visit(item, self.hub); });
    self.visits(mappedVisits);
}

self.hub.client.update = function (Visit) {
    self.newVisit.splice(0, 0, new Visit(Visit, self.hub));
}

self.hub.client.error = function (err) {
    self.error(err);
}
return self;
};

var vmVisit = new viewModel();
ko.applyBindings(vmVisit);
$.connection.hub.start().done(function () {
vmVisit.init();
});

并在视野中。

<span data-bind="    text: newVisits().length" class="badge bg-important"></span>

但不要显示任何价值。

1 个答案:

答案 0 :(得分:0)

用户是否经过身份验证?如果连接映射到用户,Signalr将仅识别用户。查看此链接,了解如何将信号器连接映射到用户:http://www.google.co.uk/url?q=http://www.asp.net/signalr/overview/guide-to-the-api/mapping-users-to-connections&sa=U&ei=Tjj-VJuPMsPBOZGGgYgH&ved=0CAsQFjAA&usg=AFQjCNFXoGJOm3mzenAJbz46TUq-Lx2bvA