从WebAPI控制器发出呼叫SignalR集线器的问题

时间:2016-03-30 07:49:02

标签: asp.net-web-api signalr

我无法弄清楚这里出了什么问题。

我已经从ASP.NET MVC WebAPI模板创建了新项目。为名为MyHub的项目添加了一个新的SignalR Hub。添加了一个加载的HTML页面,连接到Hub并发送消息。 HTML页面有一个按钮,单击该按钮将激活对APIController的post方法的ajax调用。在APIController的post方法中,我想向所有连接的客户端广播一条消息。我无法让它发挥作用。

ChatHub.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;

namespace SignalRServerAPIHub
{
    [HubName("chatHub")]
    public class ChatHub : Hub
    {
        public void Send(string message)
        {
            Clients.All.broadcastMessage(message);
        }
    }
}

的index.html

<!DOCTYPE html>
<html>
<head>
<title>SignalR Simple Chat</title>
    <style type="text/css">
        .container {
            background-color: #99CCFF;
            border: thick solid #808080;
            padding: 20px;
            margin: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <input type="text" id="message" />
        <input type="button" id="sendmessage" value="Send" />
        <input type="hidden" id="displayname" />
        <ul id="discussion"></ul>
    </div>
    <!--Script references. -->
    <!--Reference the jQuery library. -->
    <script src="Scripts/jquery-1.10.2.min.js"></script>
    <!--Reference the SignalR library. -->
    <script src="Scripts/jquery.signalR-2.2.0.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="signalr/hubs"></script>
    <!--Add script to update the page and send messages.-->
    <script type="text/javascript">
        $(function () {
            // Declare a proxy to reference the hub.
            var chat = $.connection.chatHub;
            // Create a function that the hub can call to broadcast messages.
        chat.client.broadcastMessage = function (message) {
            // Html encode display message.
                var encodedMsg = $('<div />').text(message).html();
            // Add the message to the page.
            $('#discussion').append('<li><strong>' + </strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
        };
        // Set initial focus to message input box.
        $('#message').focus();
        // Start the connection.
        $.connection.hub.start()//.done(function () {
            $('#sendmessage').click(function () {
                $.ajax({
                    url: "api/Test/PostSampleMessage",
                    data: { 'Message': $('#message').val() },
                    type: "POST"
                });
                // Clear text box and reset focus for next comment.
                $('#message').val('').focus();
            });
        //});
    });
</script>
</body>
</html>

每当连接的集线器收到新消息时,都会将新项添加到无序列表中。有一个按钮可以对TestController post方法进行Ajax调用。

API控制器

public class TestController : ApiController
{
    [HttpPost]
    public void PostSampleMessage([FromBody] FormData data)
    {
        var hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
        hubContext.Clients.All.send(data.Message);
    }
}

FormData类

public class FormData
    {
        public string Message { get; set; }
    }

Startup.cs

using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
using Microsoft.Owin.Cors;
using Microsoft.AspNet.SignalR;

[assembly: OwinStartup(typeof(SignalRServerAPIHub.Startup))]

namespace SignalRServerAPIHub
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.Map("/signalr", map =>
            {
                map.UseCors(CorsOptions.AllowAll);
                var hubConfiguration = new HubConfiguration { };
                map.RunSignalR(hubConfiguration);
            });
        }
    }
}

看起来Hub呼叫无效。我没有收到任何由此产生的错误,但没有收到客户端的消息。

感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

你应该在js中添加这样的东西:

chat.client.send= function (message) {
        alert(message)
};

或将服务器调用更改为(在您的代码中导致您尝试在客户端上调用send方法):

[HttpPost]
public void PostSampleMessage([FromBody] FormData data)
{
    var hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
    hubContext.Clients.All.broadcastMessage(data.Message);
}