我正在try 与我的react应用程序建立信号器连接,我已经在asp中创建了中心.net核心,但它似乎不会在我的前端工作.

说到信号器,我是新手,但我以前用asp.net核心的MVC应用程序,所以我知道它的逻辑工作.

但我从来没有用React处理过信号器.这就是我需要帮助的原因.

让我给你看一些代码

public class OnConnectionHub : Hub
    {
        public static int ConnectionCount { get; set; }

        public override Task OnConnectedAsync()
        {
            ConnectionCount++;
            Clients.All.SendAsync("updateConnectionCount", ConnectionCount).GetAwaiter().GetResult();
            return base.OnConnectedAsync();
        }

        public override Task OnDisconnectedAsync(Exception? exception)
        {
            ConnectionCount--;
            Clients.All.SendAsync("updateConnectionCount", ConnectionCount).GetAwaiter().GetResult();
            return base.OnDisconnectedAsync(exception);
        }
    }

相当简单,只需在OnConnectedAsyncOnDisconnectedAsync上递增和递减

这是我创建的中心url

endpoints.MapHub<OnConnectionHub>("hubs/onConnectionHub");

这是我的react组件中的一些代码

import { HubConnectionBuilder } from "@microsoft/signalr"
import { useState } from "react"

export const ConnectionCount = () => {
    const [connectionCount, setConnectionCount] = useState(0)
    // create connection
    const connection = new HubConnectionBuilder()
        .withUrl("https://localhost:7199/hubs/onConnectionHub")
        .build()

    // connect to method that hub invokes
    connection.on("updateConnectionCount", (onConnection) => {
        setConnectionCount(onConnection)
        }
    )

    // start connection
    connection.start();

    return <p>Active members {connectionCount}</p>
}

我得到的错误

react_devtools_backend.js:4026 [2022-07-14T08:31:46.444Z] Error: Failed to complete negotiation with the server: TypeError: Failed to fetch
client.onmessage @ WebSocketClient.js:50
2HttpConnection.ts:350 Uncaught (in promise) Error: Failed to complete negotiation with the server: TypeError: Failed to fetch
    at HttpConnection._getNegotiationResponse (HttpConnection.ts:350:1)
    at async HttpConnection._startInternal (HttpConnection.ts:247:1)
    at async HttpConnection.start (HttpConnection.ts:138:1)
    at async HubConnection._startInternal (HubConnection.ts:206:1)
    at async HubConnection._startWithStateTransitions (HubConnection.ts:180:1)

谢谢

推荐答案

通过更新一点公司政策解决了这个问题

builder.Services.AddCors(options =>
{
    var frontendUrl = builder.Configuration.GetValue<string>("frontend_url");
    options.AddPolicy("allowConnection", builder =>
    {
        builder.WithOrigins(frontendUrl)
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials()
            .WithExposedHeaders(new string[] { "totalAmountOfRecords" });
    });
});

创建策略而不是默认策略

app.UseCors("allowConnection");

此外,在前端

import { HubConnectionBuilder } from "@microsoft/signalr"
import { useEffect, useState } from "react"

export const ConnectionCount = () => {
    const [connectionCount, setConnectionCount] = useState(0)
    // create connection
    useEffect(() => {
        const connection = new HubConnectionBuilder()
        .withUrl("https://localhost:7199/hubs/onConnectionHub")
        .build()

    // connect to method that hub invokes
    connection.on("updateConnectionCount", (onConnection) => {
        setConnectionCount(onConnection)
        }
    )

    // start connection
    connection.start().then(() => {
        console.log("Connection started")
    });
    }, [])
    

    return(
        <section>
            <p>Active connections: {connectionCount}</p>
        </section>
    )
}

Reactjs相关问答推荐

Inbox Enum类型以React组件状态时出现TypScript错误

从`redux—thunk`导入thunk `在stackblitz中不起作用

为什么Next.js 14无法解析页面路由路径?

在Next.js中实现动态更改的服务器组件

在REACT-RUTER-DOMV6中使用通用页面包装组件有问题吗?

如何使用Reaction Testing Library+Vitest正确更新单元测试中的输入?

shadcn输入+窗体+Zod;一个部件正在改变要被控制的不受控制的输入;

FabricJS反序列化问题

REACT: UseState 没有更新变量(ant design 模态形式)

Syncfusion:带有 TabItemsDirective 的选项卡组件不显示任何内容

如何让 useEffect 在 React.JS 中只运行一次?

如何读取 null 的属性?

如何使用样式化函数为 TextField 的输入组件设置样式

ReactJS 动态禁用按钮

React JS:如何判断用户使用的是浏览器 url 还是桌面 electron

如何在 Cypress E2E 的站点上测试react 组件?

当状态改变时如何执行一些动作,但只针对第一次更新?

如何使用 useEffect 和 if 语句 React

为什么重新渲染不会影响 setTimeout 的计数?

a.active 类在导入 x.scss 文件时有效,但在使用 x.module.scss 时无效