带有 React 的 .NET 6 无法连接到 SignalR

.NET 6 with React won't connect to SignalR

我想将我的 .NET Core 5 React 项目迁移到 .NET 6,但我遇到了 SignalR 的一些问题。

我是从这篇文章开始一步步跟进的Microsoft Docs to implement SignalR with .NET 6. And still I'm getting the same error as shown here: SignalR Error Log

如有任何帮助,我们将不胜感激。我的代码片段:

Program.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllersWithViews();

builder.Services.AddSignalR();

builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(
        builder =>
        {
            builder.WithOrigins("https://localhost:44413/")
                .AllowAnyHeader()
                .WithMethods("GET", "POST")
                .AllowCredentials();
        });
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.UseCors();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller}/{action=Index}/{id?}");

app.MapFallbackToFile("index.html");
app.MapHub<ChatHub>("/chatHub");

app.Run();

ChatHub.cs

public class ChatHub : Hub
{
    public async Task SendMessage(string user, string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}

Layout.js

const connection = new SignalR.HubConnectionBuilder()
  .withUrl("/chathub")
  .configureLogging(SignalR.LogLevel.Information)
  .build();

async function start() {
  try {
    console.log("SignalR Connecting....");
    await connection.start();
    console.log("SignalR Connected.");
  } catch (err) {
    console.log(err);
    setTimeout(start, 5000);
  }
}

connection.onclose(async () => {
  await start();
});

// Start the connection.
start();

SetupProxy.js

const createProxyMiddleware = require("http-proxy-middleware");
const { env } = require("process");

const target = env.ASPNETCORE_HTTPS_PORT
  ? `https://localhost:${env.ASPNETCORE_HTTPS_PORT}`
  : env.ASPNETCORE_URLS
  ? env.ASPNETCORE_URLS.split(";")[0]
  : "http://localhost:9738";

const context = ["/weatherforecast", "/chathub"];

module.exports = function (app) {
  const appProxy = createProxyMiddleware(context, {
    target: target,
    secure: false,
    headers: {
      Connection: "Keep-Alive",
    },
  });

  app.use(appProxy);
};

对于将来遇到此问题的任何人。一旦我从代理中间件中删除 headers 并添加 ws: true (启用 websockets)。它按预期启动。

来自

const createProxyMiddleware = require("http-proxy-middleware");
const { env } = require("process");

const target = env.ASPNETCORE_HTTPS_PORT
  ? `https://localhost:${env.ASPNETCORE_HTTPS_PORT}`
  : env.ASPNETCORE_URLS
  ? env.ASPNETCORE_URLS.split(";")[0]
  : "http://localhost:9738";

const context = ["/weatherforecast", "/chathub"];

module.exports = function (app) {
  const appProxy = createProxyMiddleware(context, {
    target: target,
    secure: false,
    headers: {
      Connection: "Keep-Alive",
    },
  });

  app.use(appProxy);
};

const createProxyMiddleware = require("http-proxy-middleware");
const { env } = require("process");

const target = env.ASPNETCORE_HTTPS_PORT
  ? `https://localhost:${env.ASPNETCORE_HTTPS_PORT}`
  : env.ASPNETCORE_URLS
  ? env.ASPNETCORE_URLS.split(";")[0]
  : "http://localhost:9738";

const context = ["/weatherforecast", "/chathub"];

module.exports = function (app) {
  const appProxy = createProxyMiddleware(context, {
    target: target,
    secure: false,
    ws: true, // <-- Add this
    headers: { // <-- Remove this
      Connection: "Keep-Alive", // <-- Remove this
    }, // <-- Remove this
  });

  app.use(appProxy);
};