【问题标题】:Custom Headers and Signalr: Asp.Net MVC4 Web Api自定义标头和信号器:Asp.Net MVC4 Web Api
【发布时间】:2015-07-20 17:47:45
【问题描述】:

我在我的 asp.net mvc4 webapi 项目中使用 signalr(版本 2.0.0),

这里为了允许跨域资源共享,我在 webconfig 文件中使用了以下代码

 <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <remove name="X-Powered-By" />
  </customHeaders>

这是用于从服务器接收数据的客户端信号器代码:

 $(function () {
    var nodePublishingHub = $.connection.nodePublishingHub;
    nodePublishingHub.client.NodePublished = onNewMessage;

    $.connection.hub.error(function (error) {
        $('#messages').append('<li>' + error + '</li>');
    });

    $.connection.hub.url = "http://localhost:5441/signalr";
    $.connection.hub.start({ transport: 'longPolling' })
});

我正在使用以下代码通过信号器启用 CORS,

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

然而发生错误,

XMLHttpRequest cannot load http://localhost:5441/signalr/negotiate?connectionData=%5B%7B%22name%22%3A%…name%22%3A%22nodepublishinghub%22%7D%5D&clientProtocol=1.3&_=1386654835296. The 'Access-Control-Allow-Origin' header contains the invalid value 'null, *'. Origin 'null' is therefore not allowed access.

我该如何解决这个问题?请帮忙。

我尝试了以下,

  1. 我在 gobal.asax 中添加了这段代码,但它只使每个方法都交叉启用,所以我无法从服务器获取图像进行处理。

      HttpContext.Current.Response.Headers.Add("Access-Control-Allow-Origin", "*");
    

【问题讨论】:

    标签: asp.net-mvc-4 asp.net-web-api signalr


    【解决方案1】:

    请勿修改 signalr 原始源代码。何时更新您的代码将停止工作。

    更喜欢这个:

    $.connection.hub.start({ withCredentials: false }).done(function () {
      //...
    }
    

    start({ withCredentials: false }) 而不是典型的start() 将完成这项工作。 您可以验证here (GitHub issue tracker)官方支持。

    【讨论】:

      【解决方案2】:

      尔玛

      这应该可以解决问题

      转到您的 jquery.signalr 2.0.0.js 文件并将 withCredentials = true 更改为 false

      if (typeof (config.withCredentials) === "undefined") { config.withCredentials = false; }

      【讨论】:

      • 如果您不想更改 jquery.signalr 2.0.0.js,那么只需使用 hub.start({withCredential: false})
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-21
      • 1970-01-01
      • 2017-09-25
      • 2013-03-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多