1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

How to pass the current URL to SignalR Hub in .NET Core when using WebSockets?

Discussão em 'Angular' iniciado por Kristijan Nikoloski, Outubro 7, 2024 às 07:32.

  1. I am working with SignalR in an Angular front-end and .NET Core back-end. I need to pass the current page URL from the client to the server when establishing a SignalR connection. Initially, I tried to send it as a custom header using the headers option in the IHttpConnectionOptions, but it seems WebSockets do not support custom headers, as the Page-Url header is not available on the server side.

    Here’s my client-side code and Server side:

    this.hubConnection = new signalR.HubConnectionBuilder()
    .withUrl(apiUrl + 'sharedconnectionhub', {
    accessTokenFactory: () => accessToken,
    headers: {
    'Page-Url': window.location.href // Tried sending the current page URL here
    },
    transport: signalR.HttpTransportType.WebSockets
    })
    .withAutomaticReconnect()
    .build();



    public class MyHub : Hub
    {
    public override async Task OnConnectedAsync()
    {
    var httpContext = Context.GetHttpContext();
    if (httpContext != null)
    {
    var pageUrl = httpContext.Request.Headers["Page-Url"].ToString();
    Console.WriteLine($"Page URL: {pageUrl}");
    }

    await base.OnConnectedAsync();
    }
    }


    However, I do not see the Page-Url header on the server when using WebSockets.

    My Questions: Is there a way to pass custom headers (like the current page URL) with WebSockets in SignalR? If custom headers aren't supported with WebSockets, what is the best alternative method for passing the current URL or other custom data during a SignalR connection?

    What I've Tried: Using headers to pass the page URL (works for HTTP transport, but not for WebSockets). Retrieving the URL from httpContext.Request.Headers on the server, but the value isn't present.

    Continue reading...

Compartilhe esta Página