【问题标题】:SingalR Error during negotiation request协商请求期间的 SignalR 错误
【发布时间】:2018-05-15 08:58:56
【问题描述】:

我有一个使用 SignalR 和 AspNet 的项目。我正在尝试连接我的客户端(它是一个 cors),第一个请求返回 200 代码,但我在客户端收到此错误:

Error during negotiation request.

我的 SignalR 服务器端类:

public class Startup1
{
    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);
        });
    }
}

我的客户端js代码:

<script src="@Arbor.CVC.Common.Common.BuildServerFilePath("inc/js/jquery.signalR-2.2.3.min.js")">
</script>
<script type="text/javascript">
        $(document).ready(function () {
               var username = "";
               var id = "";
               var connection = $.hubConnection();
               var contosoChatHubProxy = connection.createHubProxy('Chat');

               connection.url = 'http://localhost:64585/signalr';
               connection.start().done(function () { 
                         console.error('Now connected, connection ID=' + connection.id); }).fail(function (e) { 
                         console.error('Could not connect ' + e); });
 </script>

请求给出了这个答案:

Url /signalr
ConnectionToken BwSsXO+oHqBNh7kqklTWTawIR7/Do3Rc4N+48KrCNzZLB37PlP0V+DnCYgW9EguJsYcjUAf6lhqz3LNd1hqJNxGJHHWbssn4YZEZQBNqeOPC8Ex7ndJfEvEfGslEvCDI
ConnectionId    352c6a53-64b9-4b45-85ce-ae7d20b33ba9
KeepAliveTimeout    20
DisconnectTimeout   30
ConnectionTimeout   110
TryWebSockets   true
ProtocolVersion 1.4
TransportConnectTimeout 5
LongPollDelay   0

但我还是得到了协商的错误。

【问题讨论】:

    标签: javascript jquery asp.net-mvc signalr signalr.client


    【解决方案1】:

    我从 Startup 中删除了 cors:

    public class Startup1
    {
        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,
                    EnableJavaScriptProxies = true,
                    EnableDetailedErrors = true
                };
                // Run the SignalR pipeline. We're not using MapSignalR
                // since this branch already runs under the "/signalr"
                // path.
                map.RunSignalR(hubConfiguration);
            });
            app.MapSignalR();
        }
    }
    

    并将标签[HubName("Chat")]添加到我的Chat.cs类中。

    我还需要定义原点,我不能使用*

    <system.webServer>
        <httpProtocol>
          <customHeaders>
              <add name="Access-Control-Allow-Origin" value="http://localhost:27947" />
              <add name="Access-Control-Allow-Methods" value="*" />
              <add name="Access-Control-Allow-Credentials" value="true" />
           </customHeaders>
        </httpProtocol>
    </system.webServer>
    

    在 JS 中:

    var connection = $.hubConnection();
    var contosoChatHubProxy = connection.createHubProxy('Chat');
    
    connection.url = 'http://localhost:64585/signalr';
    connection.start({ transport: ['webSockets', 'longPolling'] }).done(function () {console.log('Now connected, connection ID=' + connection.id);}).fail(function (e) { console.error('Could not connect ' + e); });
    

    如果您需要允许多个来源,请使用这段代码进行 web.config (IIS):

    <system.webServer>
        <httpProtocol>
          <customHeaders>    
            <add name="Access-Control-Allow-Methods" value="*" />
            <add name="Access-Control-Allow-Credentials" value="true" />
          </customHeaders>
        </httpProtocol>
        <rewrite>            
            <outboundRules>
                <clear />                
                <rule name="AddCrossDomainHeader">
                    <match serverVariable="RESPONSE_Access_Control_Allow_Origin" pattern=".*" />
                    <conditions logicalGrouping="MatchAll" trackAllCaptures="true">
                        <add input="{HTTP_ORIGIN}" pattern="(http(s)?://((.+\.)?localhost:27947|(.+\.)?localhost:26928))" />
                    </conditions>
                    <action type="Rewrite" value="{C:0}" />
                </rule>           
            </outboundRules>
        </rewrite>
      </system.webServer>
    

    【讨论】:

    • 嗨@patricia 是system.webServer 配置是在客户端还是集线器端?谢谢!很棒的帖子!
    • 另外,无法弄清楚端口指的是什么。集线器似乎在端口 64585 上运行,但规则适用于端口 27947、26928...
    • @Yaron web.config 用于集线器端。这些端口用于我要连接到集线器的不同应用程序,因此规则适用于您要连接到集线器的 url。
    • 添加 web.config 参数为我修复了它。我只有Access-Control-Allow-Origin 参数。
    猜你喜欢
    • 1970-01-01
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    • 2016-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    相关资源
    最近更新 更多