React . net -使用singalR获取所有活动连接的数量



我正试图与我的react应用程序获得一个signalR连接,我已经在asp .net core中创建了hub,但它似乎不会在我的前端工作。

我新的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进行递增和递减

这是我创建的hub 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>
)
}

最新更新