【问题标题】:Issue whille calling SignalR hub from WebAPI controller从 Web API 控制器调用 SignalR 集线器时出现问题
【发布时间】:2016-03-30 07:49:02
【问题描述】:

我不知道这里出了什么问题。

我从 ASP.NET MVC WebAPI 模板创建了新项目。向名为 MyHub 的项目添加了一个新的 SignalR Hub。添加了一个加载时连接到 Hub 并发送消息的 HTML 页面。 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);
        }
    }
}

索引.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 调用不起作用。我没有收到由此产生的任何错误,但没有为客户返回消息。

感谢任何帮助。

【问题讨论】:

    标签: asp.net-web-api signalr


    【解决方案1】:

    你应该在 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);
    }
    

    【讨论】:

    • 我包含了建议的更改,但仍然无法恢复消息。
    • 在启动连接之前在客户端启用跟踪$.connection.hub.logging = true; 并在服务器上启用new HubConfiguration { EnableDetailedErrors = true }。您将能够查看是否有错误。 reference
    • 没有收到任何错误。难道是因为启用“CORS”我没有得到回复。 Startup.cs 文件中的代码。 app.Map("/signalr", map => { map.UseCors(CorsOptions.AllowAll); var hubConfiguration = new HubConfiguration { }; map.RunSignalR(hubConfiguration); });
    • 你看看这个帖子:forums.asp.net/t/…
    • 感谢一百万,真的节省了很多时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    • 2018-10-27
    • 1970-01-01
    • 2016-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多