从控制器的WebAPI调用问题枢纽SignalR [英] calling SignalR hub from WebAPI controller issues

查看:100
本文介绍了从控制器的WebAPI调用问题枢纽SignalR的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想不通我怎么能叫成从的WebAPI ApiController一个SignalR枢纽。我已经把你可以下载一个样本<一个href=\"https://skydrive.live.com/redir?resid=EDAFB4DBECFEE2EA!23072&authkey=!AJSMQJ0RzAPlz3Y\">here它简化了问题,并演示了这个问题。

I cannot figure out how I can call into a SignalR hub from a WebAPI ApiController. I have put together a sample you can download here that simplifies the problem and demonstrates the issue.


  1. 我创建从ASP.NET MVC的WebAPI模板创建一个新的项目。

  2. 我添加了一个新的SignalR集线器名为ChatHub项目。

  3. 由一个HTML页面上的负载,连接到ChatHub,联接到一组并发送消息到该组。这个伟大的工程。

  4. HTML页面也有点击就会触发一个AJAX调用Values​​Controller的POST方法当按钮。在Values​​Controller的POST方法,我要广播消息给该组的所有连接的客户端。我不能得到这个工作。

我有只有2方法简单SignalR枢纽。

I have a simple SignalR hub with just 2 methods.

[HubName("chat")]
public class ChatHub : Hub
{
    public void Join(string room)
    {
        // NOTE: this is not persisted - ....
        Groups.Add(Context.ConnectionId, room);
    }

    public void Send(string room, string message)
    {
        var msg = String.Format(
            "{0}: {1}", Context.ConnectionId, message);
        Clients.Group(room).newMessage(msg);
    }
}

我创建一个连接到集线器聊天一个非常简单的HTML页面时,DOM准备如下图所示。

I created a very simple HTML page that connects to the Chat hub when the DOM is ready as shown here.

<html>
<head>
    <title>Simple Chat</title>
    <script src="Scripts/jquery-1.8.2.js" type="text/javascript"></script>
    <script src="Scripts/jquery.signalR-1.0.0.js"></script>
    <script src="signalr/hubs"></script>
    <script type="text/javascript">
        var chat;

        //$(function () {
        //    connectToHubs();
        //});
        $(connectToHubs);
        function connectToHubs() {
            $.connection.hub.logging = true;

            chat = $.connection.chat;
            chat.client.newMessage = onNewMessage;

            $.connection.hub.start({ transport: 'longPolling' }).done(function () {
                chat.server.join("TestGroup").done(function () {
                    chat.server.send("TestGroup", "message from html");
                });
            });

            $('#controller').click(postProficiencyUserAction);



        }
        var postProficiencyUserAction = function () {
            //var token = $('[name=__RequestVerificationToken]').val();
            var headers = {};
            //headers["__RequestVerificationToken"] = token;
            //var userAction = { createdOn: "2013-05-21T00:00:00", userId: "12345678-1234-1234-1234-000000000001", actionId: "12345678-1234-1234-1234-000000000003" };
            $.ajax({
                type: 'POST',
                url: 'http://localhost:58755/api/values',
                cache: false,
                headers: headers,
                contentType: 'application/json; charset=utf-8',
                data: 'test',
                dataType: "json",
                success: function () {

                },
                error: function () {

                }
            });
        };
        function onNewMessage(message) {
            // ... todo: validation !!!! :)
            $('#messages').append('<li>' + message + '</li>');
        };

    </script>
</head>
<body>
    <div>
        <h2>Chat</h2>
        <input type="button" id="controller" value="Controller Method" />
        <div>
            <h2>Message(s) Received</h2>
            <ul id="messages"></ul>
        </div>
    </div>
</body>
</html>

没什么特别的。每当连接集线器接收到一个新的消息,新的项被添加到无序列表。有一个按钮,使一个Ajax调用到Values​​Controller POST方法。

Nothing fancy. Whenever the connected hub receives a new message, a new item is added to the unordered list. There is a button that makes an Ajax call into the ValuesController post method.

public class ValuesController : ApiController
{
    // POST api/values
    public void Post([FromBody]string value)
    {
        var hubContext = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
        hubContext.Clients.Group("TestGroup").send("TestGroup", "Called from Controller");
    }

集线器不能正常工作。一个没有引发错误,但是,从来没有收到消息。在轮毂的发送方法把一个断点也不管用。我觉得像我这样做是正确的。谁能帮助?同样,源$ C ​​$ C可以发现<一个href=\"https://skydrive.live.com/redir?resid=EDAFB4DBECFEE2EA!23072&authkey=!AJSMQJ0RzAPlz3Y\">here

推荐答案

您所呼叫的客户端不同的方法:

You are calling different methods on the client:

API控制器

hubContext.Clients.Group("TestGroup").send("TestGroup", "Called from Controller");

集线器

Clients.Group(room).newMessage(msg);

您要呼叫的通话NewMessage作为不发送的方法

The method you want to call is newMessage not send

chat.client.newMessage = onNewMessage;

这篇关于从控制器的WebAPI调用问题枢纽SignalR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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