如何从Controller调用SignalR Core Hub方法?
我使用ASP.NET Core 2.0与Microsoft.AspNetCore.SignalR(1.0.0-alpha2-final).
我有与Excel,SolidEdge通信的Windows服务...当操作完成后,它会在ASP.NET核心应用程序中向我的控制器发送请求.现在我需要通过SignalR通知连接到服务器的所有客户端,外部程序完成了一些任务.
我无法改变窗口服务的工作方式.(无法从窗口服务连接到SignalR).
我为旧的SignalR(GlobalHost.ConnectionManager.GetHubContext)找到了很多解决方案,但是已经发生了很大变化,而且这些解决方案不再适用了.
我的控制器:
[Route("API/vardesigncomm")]
public class VarDesignCommController : Controller
{
[HttpPut("ProcessVarDesignCommResponse/{id}")]
public async Task<IActionResult> ProcessVarDesignCommResponse(int id)
{
//call method TaskCompleted in Hub !!!! How?
return new JsonResult(true);
}
}
Run Code Online (Sandbox Code Playgroud)
我的中心:
public class VarDesignHub : Hub
{
public async Task TaskCompleted(int id)
{
await Clients.All.InvokeAsync("Completed", id);
}
}
Run Code Online (Sandbox Code Playgroud) 用户在浏览器中提交表单后,我需要从服务器向客户端发送即时消息。
我按照Microsoft的步骤在此处建立了signalR连接,创建了Hub类,signalr.js等。
问题是我只能向所有客户端调用一条消息,但是我需要向发起请求的特定调用者调用该消息(否则每个人都会收到该消息)。
这是我在HomeController.cs中的POST操作:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Submit(string signalRconnectionId, Dictionary<string, string> inputs)
{
//Invoke signal to all clients sending a message to initSignal WORKS FINE
await _signalHubContext.Clients.All.SendAsync("initSignal", "This is a message from the server!");
//Invoke signal to specified client where signalRConnectionId = connection.id DOES NOT WORK
await _signalHubContext.Clients.Client(signalRconnectionId).SendAsync("initSignal", "This is a message from server to this client: " + signalRconnectionId);
return RedirectToAction("Success", inputs);
}
Run Code Online (Sandbox Code Playgroud)
我的客户javascript文件:
//Create connection and start it
const connection = new signalR.HubConnectionBuilder()
.withUrl("/signalHub") …Run Code Online (Sandbox Code Playgroud)