在ASP.NET Core 3.1中使用SignalR时,如果遇到方法未被调用的问题,可以按照以下步骤进行解决:
services.AddSignalR();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub("/yourHubRoute");
});
其中,YourHubClassName是您的Hub类的名称,yourHubRoute是Hub的URL路径。
var connection = new signalR.HubConnectionBuilder()
.withUrl("/yourHubRoute")
.build();
其中,yourHubRoute需要与服务器端的Hub端点配置一致。
public class YourHubClassName : Hub
{
public async Task YourHubMethod(string message)
{
await Clients.All.SendAsync("ReceiveMessage", message);
}
}
在客户端的JavaScript代码中,可以通过以下方式调用Hub方法:
connection.invoke("YourHubMethod", message);
其中,YourHubMethod是Hub类中定义的方法名称。
connection.start().then(function () {
connection.invoke("YourHubMethod", message);
}).catch(function (err) {
console.error(err.toString());
});
通过按照以上步骤检查和调整代码,您应该能够解决“ASP.NET Core 3.1 SignalR:方法未被调用”的问题。