SignalR客户端连接到其他服务器

时间:2019-05-18 06:51:26

标签: asp.net-mvc angular signalr

我在ASP.Net MVC应用程序中使用SignalR 2.x版,在我的角度客户端应用程序中具有相同版本的signalr。
http://localhost:42080中托管的Asp.net MVC应用程序和http://localhost:4200中托管的angular应用程序。 我已经安装了Microsoft.AspNet.SignalR并在mvc应用程序中启用了cors。

[HubName("msg")]
public class MessageHub : Hub
{
    public void Send(string user, string message)
    {
        Clients.User(user).Send(user, message);
    }
}

我想从我的角度应用程序连接到Signalr服务器,但是不能。

const connection = $.hubConnection(this.config.AdminUrl); // http://localhost:42080
const chat = connection.createHubProxy('msg'); // chat.server or chat.client are undefined

我也尝试过:

$.connection.hub.url = 'http://localhost:42080/signalr';
var hub = $.connection.msg; // hub = undefined
$.connection.hub.start() // this will result Error loading hubs. Ensure your hubs reference is correct, e.g. <script src='/signalr/js'></script>

如何连接到托管在其他服务器中的Signalr服务器?

1 个答案:

答案 0 :(得分:0)

您需要像这样配置您的Startup.cs

public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Branch the pipeline here for requests that start with "/signalr"
            app.Map("/signalr", map =>
            {
                // Setup the CORS middleware to run before SignalR.
                // By default this will allow all origins. You can 
                // configure the set of origins and/or http verbs by
                // providing a cors options with a different policy.
                map.UseCors(CorsOptions.AllowAll);
                var hubConfiguration = new HubConfiguration 
                {
                    // You can enable JSONP by uncommenting line below.
                    // JSONP requests are insecure but some older browsers (and some
                    // versions of IE) require JSONP to work cross domain
                    // EnableJSONP = true
                };
                // Run the SignalR pipeline. We're not using MapSignalR
                // since this branch already runs under the "/signalr"
                // path.
                map.RunSignalR(hubConfiguration);
            });
        }
    }

注意

  

不要在代码中将jQuery.support.cors设置为true。

     

不要将jQuery.support.cors设置为true

     

SignalR处理CORS的使用。将jQuery.support.cors设置为true   禁用JSONP,因为它使SignalR承担浏览器   支持CORS。

如果要连接到其他服务器,请在调用start方法之前指定URL,如以下示例所示:

JavaScript

$.connection.hub.url = '<yourbackendurl>;

注意

  

通常,您在调用start方法之前注册事件处理程序   建立连接。

可以找到详细信息here

相关问题