我有以下javascript调用服务器端signalR集线器。客户端代码
// A simple templating method for replacing placeholders enclosed in curly braces.
if (!String.prototype.supplant) {
String.prototype.supplant = function (o) {
return this.replace(/{([^{}]*)}/g,
function (a, b) {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
}
);
};
}
$(function () {
var checker = $.connection.LyncPresenceHub, //generated client side proxy hub
available = 'available',
busy = 'busy',
$presenceTable = $('lyncPresence'),
$presenceBody = $presenceTable.find('tbody'),
rowTemplate = '<tr data-id="{Name}"><td><div class="{Status}"></div></td><td><div class="{Name}"></td></tr>';
function formatPresence(lyncUser) {
return $.extend(lyncUser, {
Name: lyncUser.UserName,
Status: lyncUser.Presence
});
}
function init() {
checker.server.GetAllUsers()
.done(function (lyncUsers) {
$presenceTable.empty();
$.each(lyncUsers, function () {
var user = formatPresence(this);
$presenceBody.append(rowTemplate.supplant(user));
});
});
}
//Client side hub method which will be called by the server
checker.client.updateLyncUserPresence = function (LyncUser) {
var displayPresence = formatPresence(LyncUser);
$row = $(rowTemplate.supplant(displayPresence));
$presenceBody.find('tr[data-id=' + LyncUser.Name + ']')
.replaceWith($row);
}
$.connection.hub.start().done(init);
});
SignalR集线器代码(C#)如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using Oobe.Bobs.Lync.Models;
namespace xxx {
[HubName("LyncPresenceHub")]
public class LyncPresenceHub : Hub
{
private readonly LyncPresenceChecker _lyncpresenceChecker;
public LyncPresenceHub() : this(LyncPresenceChecker.Instance) { }
public LyncPresenceHub(LyncPresenceChecker checker)
{
_lyncpresenceChecker = checker;
}
public IEnumerable<LyncUser> GetAllUsers()
{
return _lyncpresenceChecker.GetAllUsers();
}
}
}
我得到的错误如下。 Object不支持属性或方法“GetAllUsers”
答案 0 :(得分:2)
您的问题是JavaScript中不存在GetAllUsers
。这是因为,默认情况下,SignalR接受第一个字母,如果它是大写的则使其为小写。您可以使用[HubMethodName(string)]
属性覆盖此默认行为,如MSDN in this article所示(和解释):
在客户端上,代理名称是Hub类名称的驼峰版本。 SignalR自动进行此更改,以便JavaScript代码符合JavaScript约定。
public class ContosoChatHub : Hub
{
[HubMethodName("NewContosoChatMessage")]
public void NewContosoChatMessage(string name, string message)
{
Clients.All.addContosoChatMessageToPage(name, message);
}
}