由于 cors 问题,无法使 Signal R 工作 - 被 cors 策略阻止

Pau*_*aul 4 cors signalr reactjs cors-anywhere

我正在使用 React 和 Signal R

我有一个托管我的集线器的标准 Web 应用程序。

当我发送消息时,网络应用程序的网页中的所有内容都完美运行

我还有一个托管在端口 3000 上的 React 应用程序

我按照以下方式更改了 IIS Express 设置

    <httpProtocol>
      <customHeaders>
        <clear />
        <add name="X-Powered-By" value="ASP.NET" />
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
      </customHeaders>
      <redirectHeaders>
        <clear />
      </redirectHeaders>
    </httpProtocol>
Run Code Online (Sandbox Code Playgroud)

我的 cors 等服务器端启动如下

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
        services.AddCors(options =>
        {
            options.AddPolicy("cors",
                builder =>
                {
                    builder
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .WithOrigins("http://localhost:3000");
                });
        });

        services.AddSignalR();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseCors("cors");
        app.UseStaticFiles();
        app.UseRouting();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<ChatHub>("/chatHub");
            endpoints.MapRazorPages();
        });
    }
Run Code Online (Sandbox Code Playgroud)

在 React 方面,我实现如下

import React, { Component } from 'react';
import * as signalR from '@aspnet/signalr';

class Chat extends Component {
  constructor(props) {
    super(props);

    this.state = {
      nick: '',
      message: '',
      messages: [],
      hubConnection: null,
    };
  }

  componentDidMount = () => {
    const protocol = new signalR.JsonHubProtocol();
    const transport = signalR.HttpTransportType.WebSockets;

    const options = {
      transport,
      logMessageContent: true,
      logger: signalR.LogLevel.Trace,
    };

    // create the connection instance
    var hubConnection = new signalR.HubConnectionBuilder()
      .withUrl("http://localhost:44360/chatHub", options)
      .withHubProtocol(protocol)
      .build();

    this.setState({ hubConnection }, () => {
      this.state.hubConnection
        .start()
        .then(() => console.log('Connection started!'))
        .catch(err => console.log('Error while establishing connection :('));

      this.state.hubConnection.on('SendMessage', (user, message) => {
        const text = `${user}: ${message}`;
        const messages = this.state.messages.concat([text]);

        console.log('ssss');

        this.setState({ messages });
      });
    });
  }

  render() {
    return (
      <div>
        <br />

        <div>
          {this.state.messages.map((message, index) => (
            <span style={{display: 'block'}} key={index}> {message} </span>
          ))}
        </div>
      </div>
    );
  }
}

export default Chat;
Run Code Online (Sandbox Code Playgroud)

如您所见,我已连接到我的服务器应用程序所在的确切端口

我在日志中看到一个条目表明我已连接

但是,我实际上从未收到过任何消息?

我在网络应用程序中的中心如下所示

"use strict";

var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();

//Disable send button until connection is established
document.getElementById("sendButton").disabled = true;

connection.on("ReceiveMessage", function (user, message) {
    var msg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
    var encodedMsg = user + " says " + msg;
    var li = document.createElement("li");
    li.textContent = encodedMsg;
    document.getElementById("messagesList").appendChild(li);
});

connection.start().then(function () {
    document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
    return console.error(err.toString());
});

document.getElementById("sendButton").addEventListener("click", function (event) {
    var user = document.getElementById("userInput").value;
    var message = document.getElementById("messageInput").value;
    connection.invoke("SendMessage", user, message).catch(function (err) {
        return console.error(err.toString());
    });
    event.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)

我以为我已经解决了 Cors 问题,但是当我将网页打开一段时间时,我收到了错误

Access to XMLHttpRequest at 'http://localhost:44360/chatHub/negotiate' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Run Code Online (Sandbox Code Playgroud)

谁能看到我做错了什么吗?

Pau*_*aul 8

经过几个小时的尝试我终于让它工作了

我将把这个问题和我的解决方案保留在这里以帮助其他人

首先 - 在配置服务中:

  public void ConfigureServices(IServiceCollection services)
  {
    services.AddRazorPages();
    services.AddCors();
    services.AddSignalR();
  }
Run Code Online (Sandbox Code Playgroud)

确保 Cors 位于 Signal R 之前

然后在配置中

        // Make sure the CORS middleware is ahead of SignalR.
        app.UseCors(builder =>
        {
            builder.WithOrigins("http://localhost:3000") //Source
                .AllowAnyHeader()
                .WithMethods("GET", "POST")
                .AllowCredentials();
        });

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<MYHubClass>("/myHub");
        });
Run Code Online (Sandbox Code Playgroud)

确保 UseCors 位于 UseEndpoints 之前