客户端永远不会从生产中的控制器 .NET Core 接收来自信号中心的 SendAsync 调用消息

发布于 2025-01-18 12:11:03 字数 3756 浏览 0 评论 0原文

这在本地起作用,没有任何问题,但是当将客户端在控制器中调用REST端点时,将其部署到Azure App Service时,我永远不会收到任何消息。

我的应用程序服务具有Web插座通过Azure中的配置设置在服务器上启用。

引用有关如何在枢纽外使用HubContext的文档: https://learn.microsoft.com/en-us/aspnet/core/signalr/signalr/hubcontext

[2022-04-01T19:34:40.915Z] Information: WebSocket connected to wss://staging-env.com/hubs/notification?id=omz2rGgyuXw01QV6Vs6PbA.

noreferrer 客户端成功:

Testing notification hub broadcasting 4/1/2022 7:34:40 PM

没有有关封闭连接的错误消息或信息 - 在应用程序日志中正确ping。

我有一个控制器:

public class NotificationHubController : ControllerBase
{
    private readonly IHubContext<NotificationHub> _hub;
    private readonly ILogger<NotificationHubController> _logger;
    
    public NotificationHubController(
        ILogger<NotificationHubController> logger,
        IHubContext<NotificationHub> hub
    )
    {
            _logger = logger;
            _hub = hub;
    }

    [HttpPost]
    public async Task<IActionResult> SendNotification(NotificationDto dto)
    {
        _logger.LogInformation("Broadcasting notification update started");
        await _hub.Clients.All.SendAsync("NotificationUpdate", dto);  <-------- no errors reported
        _logger.LogInformation("Broadcasting notification update resolved");
        return Ok();
    }

}

集线器:

using Microsoft.AspNetCore.SignalR;

namespace NMA.Api.Service.Hubs
{
    public class NotificationHub: Hub
    {
        public Task NotifyConnection()
        {
            return Clients.All.SendAsync("TestBrodcasting", $"Testing notification hub 
                     broadcasting {DateTime.Now.ToLocalTime()}");
        }
    }
}

启动:

...
            services.AddSignalR(hubOptions =>
            {
                hubOptions.EnableDetailedErrors = true;
            });

...
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapHub<NotificationHub>("/hubs/notification");
                endpoints.MapControllers();
            });

客户端:(

react js Hook)

export const useNotificationHub = ({ onNotificationRecievedCallback }: NotificationHubProps) => {
    const [connection, setConnection] = useState<HubConnection | null>(null);

    useEffect(() => {
        const establishConnection = async () => {
            const newConnection = new HubConnectionBuilder()
                .withUrl(`${process.env.REACT_APP_NMA_HUB_URL}/notification`)
                .withAutomaticReconnect()
                .build();

            await newConnection.start();

            newConnection.invoke("NotifyConnection").catch(function (err) {
                console.error(err.toString());
            });

            newConnection.on("TestBrodcasting", function (time) {   
                console.log(time);
            });

            newConnection.on('NotificationUpdate', (response: NotificationAPIResponse) => {
                console.log("Notification Recieved: ", response);
                onNotificationRecievedCallback(response);
            });

            newConnection.onclose(() => {
                console.log("Notification connection hub closed");
            })

            setConnection(newConnection);
        }

        establishConnection();

    }, [onNotificationRecievedCallback]);

    return {
    }
}

我通过失眠来提出请求,以通过端点发布通知。我获得了成功的HTTP状态返回。我的日志告诉我,通话是成功的。但是未收到的数据。

我不确定该怎么办。我需要能够从休息端点调用客户端呼叫,但这似乎不起作用,我已经用力使用Google找到替代方案的能力。

This works locally without any issues however when deployed to azure app service my client never receives any message when calling REST endpoint in controller.

My App Service has Web sockets enabled on the server via the configuration settings in azure.

Referencing docs for how to use the hubcontext outside of the hub: https://learn.microsoft.com/en-us/aspnet/core/signalr/hubcontext?view=aspnetcore-6.0

I have a successful opened a connection:

[2022-04-01T19:34:40.915Z] Information: WebSocket connected to wss://staging-env.com/hubs/notification?id=omz2rGgyuXw01QV6Vs6PbA.

I receive test broadcast we call from the client successfully:

Testing notification hub broadcasting 4/1/2022 7:34:40 PM

No error messages or information regarding a closed connection - everything pinging correctly in app logs.

I have a controller:

public class NotificationHubController : ControllerBase
{
    private readonly IHubContext<NotificationHub> _hub;
    private readonly ILogger<NotificationHubController> _logger;
    
    public NotificationHubController(
        ILogger<NotificationHubController> logger,
        IHubContext<NotificationHub> hub
    )
    {
            _logger = logger;
            _hub = hub;
    }

    [HttpPost]
    public async Task<IActionResult> SendNotification(NotificationDto dto)
    {
        _logger.LogInformation("Broadcasting notification update started");
        await _hub.Clients.All.SendAsync("NotificationUpdate", dto);  <-------- no errors reported
        _logger.LogInformation("Broadcasting notification update resolved");
        return Ok();
    }

}

Hub:

using Microsoft.AspNetCore.SignalR;

namespace NMA.Api.Service.Hubs
{
    public class NotificationHub: Hub
    {
        public Task NotifyConnection()
        {
            return Clients.All.SendAsync("TestBrodcasting", 
quot;Testing notification hub 
                     broadcasting {DateTime.Now.ToLocalTime()}");
        }
    }
}

Startup:

...
            services.AddSignalR(hubOptions =>
            {
                hubOptions.EnableDetailedErrors = true;
            });

...
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapHub<NotificationHub>("/hubs/notification");
                endpoints.MapControllers();
            });

Client:

(react js hook)

export const useNotificationHub = ({ onNotificationRecievedCallback }: NotificationHubProps) => {
    const [connection, setConnection] = useState<HubConnection | null>(null);

    useEffect(() => {
        const establishConnection = async () => {
            const newConnection = new HubConnectionBuilder()
                .withUrl(`${process.env.REACT_APP_NMA_HUB_URL}/notification`)
                .withAutomaticReconnect()
                .build();

            await newConnection.start();

            newConnection.invoke("NotifyConnection").catch(function (err) {
                console.error(err.toString());
            });

            newConnection.on("TestBrodcasting", function (time) {   
                console.log(time);
            });

            newConnection.on('NotificationUpdate', (response: NotificationAPIResponse) => {
                console.log("Notification Recieved: ", response);
                onNotificationRecievedCallback(response);
            });

            newConnection.onclose(() => {
                console.log("Notification connection hub closed");
            })

            setConnection(newConnection);
        }

        establishConnection();

    }, [onNotificationRecievedCallback]);

    return {
    }
}

I make the request via Insomnia to post a notification via the endpoint. I get a successful HTTP status return. My logs tell me that the that the call was made and it was successful. Yet not data received in the client.

I'm not sure what to do from here. I need to be able to invoke client calls from REST endpoints but this doesn't seem to work and I've exhausted my ability to use google to find alternatives.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

违心° 2025-01-25 12:11:03

我相信您遇到此问题是因为您正在启动连接,然后最后设置 ononclose 回调。您应该首先设置所有回调,然后启动连接应该是您要做的最后一件事。

例如:

    // BUILD THE CONNECTION FIRST

    const newConnection = new HubConnectionBuilder()
        .withUrl(`${process.env.REACT_APP_NMA_HUB_URL}/notification`)
        .withAutomaticReconnect()
        .build();

        // SET UP CALLBACKS SECOND

        newConnection.on("TestBrodcasting", function (time) {   
            console.log(time);
        });

        newConnection.on('NotificationUpdate', (response: NotificationAPIResponse) => {
            console.log("Notification Recieved: ", response);
            onNotificationRecievedCallback(response);
        });

        newConnection.onclose(() => {
            console.log("Notification connection hub closed");
        })

        // START CONNECTION LAST

        await newConnection.start();

        // NOW YOU CAN INVOKE YOUR METHOD

        newConnection.invoke("NotifyConnection").catch(function (err) {
            console.error(err.toString());
        });

I believe you are experiencing the issue because you are starting the connection and then setting up the on and onclose callbacks last. You should rather set up all of your callbacks first, and then starting the connection should be the last thing you do.

EG:

    // BUILD THE CONNECTION FIRST

    const newConnection = new HubConnectionBuilder()
        .withUrl(`${process.env.REACT_APP_NMA_HUB_URL}/notification`)
        .withAutomaticReconnect()
        .build();

        // SET UP CALLBACKS SECOND

        newConnection.on("TestBrodcasting", function (time) {   
            console.log(time);
        });

        newConnection.on('NotificationUpdate', (response: NotificationAPIResponse) => {
            console.log("Notification Recieved: ", response);
            onNotificationRecievedCallback(response);
        });

        newConnection.onclose(() => {
            console.log("Notification connection hub closed");
        })

        // START CONNECTION LAST

        await newConnection.start();

        // NOW YOU CAN INVOKE YOUR METHOD

        newConnection.invoke("NotifyConnection").catch(function (err) {
            console.error(err.toString());
        });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文