【发布时间】:2021-01-21 04:25:49
【问题描述】:
我的 SignalR 客户端没有收到来自服务器的任何消息。我在这里错过了什么?
服务器集线器
namespace DoneITWebAPI.Hubs
{
public interface ITypedHubClient
{
Task BroadcastMessage(string name, string message);
}
public class ServiceStatusHub : Hub<ITypedHubClient>
{
public void Send(string name, string message)
{
Clients.All.BroadcastMessage(name, message);
}
}
}
控制器
[Route("api/[controller]")]
[ApiController]
public class DemoController : Controller
{
IHubContext<ServiceStatusHub, ITypedHubClient> _chatHubContext;
public DemoController(IHubContext<ServiceStatusHub, ITypedHubClient> chatHubContext)
{
_chatHubContext = chatHubContext;
}
// GET: api/values
[HttpGet]
public IEnumerable<string> Get()
{
_chatHubContext.Clients.All.BroadcastMessage("ReceiveMessage", "test");
return new string[] { "value1", "value2" };
}
}
控制台客户端应用
class Program
{
static void Main(string[] args)
{
var connection = new HubConnectionBuilder()
.WithUrl("http://localhost:64165/ServiceStatusHub")
.Build();
connection.On<string, string>("ReceiveMessage", (user, message) =>
{
GetMessage(user, message);
});
connection.StartAsync();
Console.ReadKey();
}
public static void GetMessage(string user, string message)
{
//Not hitting here
}
}
【问题讨论】:
-
你检查连接建立了吗?
-
您能否向我们展示一下,您如何在
Startup.cs中注册您的集线器以及如何实际发送您想要接收的消息?
标签: c# asp.net-core asp.net-core-webapi asp.net-core-signalr