【问题标题】:Signal R Server Client "Access-Control-Allow-Origin" missing errorSignalr 服务器客户端“Access-Control-Allow-Origin”缺失错误
【发布时间】:2017-05-11 13:47:39
【问题描述】:

我正在试用 Signal R 并构建了一个作为 Windows 服务运行的服务器 dll(Windows 服务库/c#)。我还构建了一个客户端应用程序(asp.net Web 应用程序)来与服务器通信。

但我总是收到错误(Firefox)“Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%5D&_=1482829095207. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

Chrome 错误“

Failed to load resource: the server responded with a status of 400 (Bad Request)"
XMLHttpRequest cannot load http://localhost:8080/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%5D&_=1482830200155. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:50259' is therefore not allowed access. The response had HTTP status code 400.

注意:Edge 和 IE 都会出现错误

我已经阅读了 Stackoverflow 上几乎所有关于这个主题的帖子,但这些解决方案似乎都不起作用。

我用于服务器端的代码:

namespace SignalRService
{

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

Services.cs

public void StartService()
{
    LogMessage("SignalRService started", true);
    Running = true;
    WebApp.Start<StartupConfiguration>(ConfigurationManager.AppSettings["SignalRServerUrl"]);
}

EnvironmentSettings.config:

<add key="SignalRServerUrl" value="http://localhost:8080"/>

Hubs.cs

namespace SignalRService.Hubs
{
    [HubName("TestHub")]
    public class TestHub: Hub
    {
        public static Dictionary<string, List<HubClient>> clients = new Dictionary<string, List<HubClient>>();

        [HubMethodName("Subscribe")]
        public async Task Subscribe(string Id)
        {...... }}

客户端(Javascript/Jquery)

 var signalrHubConnection;
    var signalrHubConnectionProxy;
    var signalRServerUrl = "http://localhost:8080";

    var currentTimeout;
    var count = 0;

    var startSignalRConnection = function () {
        console.log("Start");

        signalrHubConnection = $.hubConnection(signalRServerUrl);
        console.log("Running");
        signalrHubConnection.logging = true;
        signalrHubConnectionProxy = signalrHubConnection.createHubProxy('TestHub');


        console.log("--Subscribe starting");
        signalrHubConnection.start()
            .done(function () {

                signalrHubConnectionProxy.invoke('Subscribe', Id.toString());
                console.log("Subscribe ending");
            })
            .fail(function (test) {
                if (count < 5) {
                    console.log(test.toString());
                    clearTimeout(currentTimeout);
                    currentTimeout = setTimeout(function () {
                        count++;
                        startSignalRConnection();
                    }, 300000); // retry after 5 minutes
                }
            }
        );

        signalrHubConnectionProxy.on('IncomingMessage',
            function (message) {
                console.log("Message = " + message.toString());
            }
        );
    };

Test.aspx

<script src="https://code.jquery.com/jquery-3.1.1.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/signalr/jquery.signalr-2.2.1.min.js"></script>

我有什么问题吗?

【问题讨论】:

  • 你有没有想出解决办法?

标签: c# asp.net cors signalr


【解决方案1】:

错误暗示 SignalR url 与请求 url 不同(来源)。因此,SignalR 在 localhost 上,但您的主网站(包含客户端示例的网站)显然是使用“localhost”访问的。

也许您正在使用 IP(例如 http://127.0.0.1/)或您的 PC 名称(例如 http://badassPC/)访问它,而它们必须在默认 SignalR 设置下匹配。我很确定端口是否不同无关紧要,如果它们在同一个域上也无关紧要(例如 www.mysite.com 和 signalr.mysite.com)

请注意,除非您真的知道自己在做什么,否则我不会推荐一种解决方法,否则会有相当严重的安全风险:https://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client#crossdomain

【讨论】:

    猜你喜欢
    • 2015-12-16
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    • 1970-01-01
    • 1970-01-01
    • 2016-12-28
    • 2017-05-08
    相关资源
    最近更新 更多