c# - 从 Controller .Net Core 2.1 调用 Signalr 方法
问题描述
我正在尝试从(ASP.NET Core)MVC 控制器调用信号器 Hub 类中的方法,但我无法在网上找到一个示例来说明如何操作。
注意:有很多使用 .Net Framework 的旧版本信号器的示例,但我看不到如何在 .Net Core 中执行此操作。
我需要将 MVC 操作结果中的 id 直接传递到我的集线器,而不将 id 传递到页面,然后必须将客户端连接返回到集线器。
public class ChatHub : Hub
{
public async Task DoSomething(int id)
{
//// Something in here.
}
}
public class HomeController : Controller
{
private readonly IHubContext<ChatHub> _hubContext;
public HomeController(IHubContext<ChatHub> hubContext)
{
_hubContext = hubContext;
}
public async Task<ActionResult> Index(int id)
{
//// Call the DoSomething method from here, passing the id across.
await _hubContext.Clients.All.SendAsync("AddToGroup", groupId);
}
}
请问有没有办法做到这一点?(或者我看错了,有没有更好的方法来达到同样的结果?)
更新:如果我将 Id 传递到视图中,然后使用 JavaScript 调用 Hub,然后调用 DoSomething 方法,因此我可以看到它正确地挂在一起,但当我尝试在 C# 中调用它时却没有。
解决方案
我认为您误解了这一切是如何协同工作的(直到昨天我都做了同样的事情),集线器代码用于客户端脚本代码回调然后执行操作,而 IHubContext 用作将发送到客户端的强类型方法
中心
// This class is used by the JavaScript Client to call into the .net core application.
public class ChatHub : Hub<IChatClient>
{
public static ConcurrentDictionary<string, string> Connections = new ConcurrentDictionary<string, string>();
// As an example, On connection save the user name with a link to the client Id for later user callback
public override Task OnConnectedAsync()
{
var user = Context.User.Identity.Name;
Connections.AddOrUpdate(this.Context.ConnectionId, user, (key, oldValue) => user);
return base.OnConnectedAsync();
}
public override Task OnDisconnectedAsync(Exception exception)
{
// Do something on disconnect.
}
// Add other methods you want to be able to call from JavaScript side in here...
public void SendMessage(int id, string message)
{
// Message doing stuff here.
}
}
聊天客户端接口
// This provides strongly-typed methods that you'll have on the Client side but these don't exist on the server.
public interface IChatClient
{
//So this method is a JS one not a .net one and will be called on the client(s)
Task DoSomething(int id);
Task NotificationUpdate(int id, string message);
}
控制器
public class HomeController : Controller
{
private readonly IHubContext<ChatHub, IChatClient> _hubContext;
public HomeController(IHubContext<ChatHub, IChatClient> hubContext)
{
_hubContext = hubContext;
}
public async Task<ActionResult> Index(int id)
{
// This calls the method on the Client-side
await _hubContext.Clients.All.DoSomething(id);
}
}
推荐阅读
- python - 如何使用文本文件中的值在 python 中创建曲面图?
- python - understanding iteration of python values
- javascript - 如何在javascript中获取自定义谷歌搜索的预填充结果
- html - Why is CSS clear property not clearing floats?
- .net - Open CMD and run command from VB.net
- php - 无法通过身份验证访问 API
- intellij-idea - IntelliJ: custom code generation templates
- managedobjectcontext - Core Data ManagedObjectContext 和 Private Queue,父上下文的作用
- c# - 使用 Natcorder Video 的帧?
- amazon-web-services - AWS - 缓存预定 lambda 函数的响应