从Controller调用SignalR Core Hub方法 [英] Call SignalR Core Hub method from Controller
问题描述
如何从Controller调用SignalR Core Hub方法?
我正在将ASP.NET Core 2.0与Microsoft.AspNetCore.SignalR(1.0.0-alpha2-final)一起使用.
How can I call SignalR Core Hub method from Controller?
I am using ASP.NET Core 2.0 with Microsoft.AspNetCore.SignalR (1.0.0-alpha2-final).
我有与Excel,SolidEdge和Excel通信的Windows服务...完成操作后,它将请求发送到ASP.NET Core应用程序中的控制器.现在,我需要通知所有与SignalR连接到服务器的客户端,外部程序已完成某些任务.
我无法更改窗口服务的工作方式. (无法从窗口服务连接到SignalR.)
我为旧的SignalR(GlobalHost.ConnectionManager.GetHubContext
)找到了很多解决方案,但是发生了很多变化,这些解决方案不再起作用.
I have windows service which communicate with Excel, SolidEdge ... When operation is complete it post request to my controller in ASP.NET Core application. Now I need to inform all clients connected to server with SignalR that external program completed some task.
I can not change the way window service works. (Can not connect to SignalR from window service).
I found plenty solution for old SignalR (GlobalHost.ConnectionManager.GetHubContext
), but much has changed and those solutions are not working anymore.
我的控制器:
[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);
}
}
我的中心:
public class VarDesignHub : Hub
{
public async Task TaskCompleted(int id)
{
await Clients.All.InvokeAsync("Completed", id);
}
}
推荐答案
解决方案1
另一种可能性是将HubContext注入到控制器中,例如:
Another possibility is to inject your HubContext into your controller like:
public VarDesignCommController(IHubContext<VarDesignHub> hubcontext)
{
HubContext = hubcontext;
...
}
private IHubContext<VarDesignHub> HubContext
{ get; set; }
那你也可以打电话
await this.HubContext.Clients.All.InvokeAsync("Completed", id);
但是随后您将在所有客户端上定向调用方法.
But then you will direct call methods on all clients.
解决方案2
您还可以使用类型化的集线器: 简单创建一个接口,您可以在其中定义服务器可以在客户端上调用的方法:
You can also work with typed hubs: Simple create an interface where you define which methods your server can call on the clients:
public interface ITypedHubClient
{
Task BroadcastMessage(string name, string message);
}
从集线器继承:
public class ChatHub : Hub<ITypedHubClient>
{
public void Send(string name, string message)
{
Clients.All.BroadcastMessage(name, message);
}
}
将类型化的hubcontext注入到控制器中,并对其进行处理:
Inject your the typed hubcontext into your controller, and work with it:
[Route("api/demo")]
public class DemoController : Controller
{
IHubContext<ChatHub, ITypedHubClient> _chatHubContext;
public DemoController(IHubContext<ChatHub, ITypedHubClient> chatHubContext)
{
_chatHubContext = chatHubContext;
}
// GET: api/values
[HttpGet]
public IEnumerable<string> Get()
{
_chatHubContext.Clients.All.BroadcastMessage("test", "test");
return new string[] { "value1", "value2" };
}
}
这篇关于从Controller调用SignalR Core Hub方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!