我遇到以下 SignalR 问题:
服务器代码:
public class ConnectionHandlerModel
{
public static Collection<ConnectedDigiModel> Digis = new Collection<ConnectedDigiModel>();
}
public class ConnectedDigiModel
{
public string ConnectionID = "";
public string DeviceNr = "";
public string GroupName = "";
public string UserName = "";
public ConnectedDigiModel(string ConnectionID, string username)
{
this.ConnectionID = ConnectionID;
this.UserName = username;
}
}
public override async Task OnConnectedAsync()
{
var username = Context.GetHttpContext().Request.Query["username"];
ConnectionHandlerModel.Digis.Add(new ConnectedDigiModel(Context.ConnectionId, username));
}
public async Task SendConnectedDigis()
{
await Clients.Caller.SendAsync("ConnectedDigisToSTM", ConnectionHandlerModel.Digis);
}
客户端代码:
private async void btnGetConnectedDigis_Click(object sender, EventArgs e)
{
await digiConnection.InvokeAsync("SendConnectedDigis");
}
digiConnection.On<Collection<ConnectedDigiModel>>("ConnectedDigisToSTM", (digis) =>
{
foreach (ConnectedDigiModel digi in digis)
{
listBox1.Invoke(new MethodInvoker(delegate () { listBox1.Items.Add(digi.UserName.ToString()); }));
}
});
问题: 最后一个方法没有触发。
我将其更改为仅发送一个字符串并且它有效。为什么集合作为参数会阻止方法执行?
我找到了答案。似乎您用作信号器参数的类必须具有设置器和获取器。
这有效:
公共类 ConnectedDigiModel { 公共字符串 ConnectionID { 获取;放; } 公共字符串设备编号 { 获取;放; } 公共字符串组名 { get;放; } 公共字符串用户名{获取;放; }
public ConnectedDigiModel(string ConnectionID, string username) { this.ConnectionID = ConnectionID; this.UserName = username; } }