SignalR +通过一个操作方法发布消息到集线器 [英] SignalR + posting a message to a Hub via an action method

查看:1238
本文介绍了SignalR +通过一个操作方法发布消息到集线器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用SignalR的hub-功能( https://github.com/SignalR/SignalR )发布消息所有订阅的客户端:

I am using the hub- feature of SignalR (https://github.com/SignalR/SignalR) to publish messages to all subscribed clients:

public class NewsFeedHub : Hub
public void Send(string channel, string content)
{
    Clients[channel].addMessage(content);
}

这打电话时发送通过Javascript,但我也想在Web应用程序发布消息(从ASP.NET MVC操作方法内)工作正常。我已经尝试过实例化一个新的对象ob NewsFeedHub并调用发送方法,但这会导致一个错误(如集线器的潜在连接未设置)。有没有办法使用集线器没有连接的方法吗?

This works fine when calling "Send" via Javascript, but I would also like the web application to publish messages (from within an ASP.NET MVC action method). I already tried instantiating a new object ob NewsFeedHub and calling the Send method, but this results in an error (as the underlying "Connection" of the Hub is not set). Is there a way to use the Hub without a connection?

推荐答案

请注意,SignalR API已经更改多次因为这个问题被问。有机会的话,有些答案会变得过时。这并不意味着它们应该被向下投票,因为他们在写本新闻时是正确

有是该另一个更新的答案,如在的 SignalR维基

There is another updated answer for this, as seen in the SignalR Wiki

C#

Public ActionResult MyControllerMethod()
{
    var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
    context.Clients.All.methodInJavascript("hello world");
    // or
    context.Clients.Group("groupname").methodInJavascript("hello world");
}

vb.net

vb.net

Public Function MyControllerMethod() As ActionResult
    Dim context = GlobalHost.ConnectionManager.GetHubContext(Of MyHub)()
    context.Clients.All.methodInJavascript("hello world")
    '' or
    context.Clients.Group("groupname").methodInJavascript("hello world")
End Function

更新

这code已被更新。按照<一href=\"http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-server\">http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-server更改。

This code has been updated. Follow http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-server for changes.

这篇关于SignalR +通过一个操作方法发布消息到集线器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆