gpt4 book ai didi

reactjs - React .NET - 使用 signalR 获取所有事件连接的数量

转载 作者:行者123 更新时间:2023-12-05 02:27:43 24 4
gpt4 key购买 nike

我正在尝试与我的 React 应用程序建立 signalR 连接,我已经在 asp .net 核心中创建了集线器,但它似乎无法在我的前端工作。

我是 signalR 的新手,但我之前使用 asp .net 核心 MVC 应用程序创建过它,所以我知道逻辑是有效的。

但我从未使用 React 对 signalR 做过任何事情。所以这就是为什么我需要一些帮助。

让我给你看一些代码SignalR 中心

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)

谢谢!

最佳答案

通过稍微更新 corspolicy 解决了这个问题像这样

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 - React .NET - 使用 signalR 获取所有事件连接的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72977588/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com