简体   繁体   中英

SignalR : Send a Message for special user

I have a model that i want to send message for special user when add new item of my model.

I add a hub.

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; }
}

and in Controller, when i add item.

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

and in 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();
});

and in view.

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

But don't show any value.

Is the user authenticated? Signalr will only recognize the user if the connections are mapped to the user. Check this link on how to map signalr connections to users: 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM