Blazor SignalR failre

Posted 1 year ago by buda56
0

Hi,

  Hopefully someone can point me in the right direction to resolve this problem, I have setup another SignalR hub in my blazor Server application and am getting the following failure when trying to access the page that the SignalR hub is supposed to be connected to for auto updates.

   System.Net.Http.HttpRequestException: Response status code does not indicate success: 500 (Internal Server Error).

      at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()

      at Microsoft.AspNetCore.Http.Connections.Client.HttpConnection.NegotiateAsync(Uri url, HttpClient httpClient, ILogger logger, CancellationToken cancellationToken)

      at Microsoft.AspNetCore.Http.Connections.Client.HttpConnection.GetNegotiationResponseAsync(Uri uri, CancellationToken cancellationToken)

      at Microsoft.AspNetCore.Http.Connections.Client.HttpConnection.SelectAndStartTransport(TransferFormat transferFormat, CancellationToken cancellationToken)

      at Microsoft.AspNetCore.Http.Connections.Client.HttpConnection.StartAsyncCore(TransferFormat transferFormat, CancellationToken cancellationToken)

      at Microsoft.AspNetCore.Http.Connections.Client.HttpConnection.StartAsync(TransferFormat transferFormat, CancellationToken cancellationToken)

      at Microsoft.AspNetCore.Http.Connections.Client.HttpConnectionFactory.ConnectAsync(EndPoint endPoint, CancellationToken cancellationToken)

      at Microsoft.AspNetCore.Http.Connections.Client.HttpConnectionFactory.ConnectAsync(EndPoint endPoint, CancellationToken cancellationToken)

      at Microsoft.AspNetCore.SignalR.Client.HubConnection.StartAsyncCore(CancellationToken cancellationToken)

      at Microsoft.AspNetCore.SignalR.Client.HubConnection.StartAsyncInner(CancellationToken cancellationToken)

      at Microsoft.AspNetCore.SignalR.Client.HubConnection.StartAsync(CancellationToken cancellationToken)

      at RevIntra.UI.Base.Pages.Revroof.RevbendOrderListViewPage.OnInitializedAsync() in D:\Shared\Source\Repos\Revroof\RevIntra_BP\RevIntra\Shared\RevIntra.UI.Base\Pages\Revroof\RevbendOrderListViewPage.cs:line 75

      at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()

      at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)

 

My code kicks off from the follwing..

    protected override async Task OnInitializedAsync()

       {

           userInfo = await ((IdentityAuthenticationStateProvider)authStateProvider).GetUserViewModel();

           

           _hubConnection = new HubConnectionBuilder()

               .WithUrl(NavigationManager.ToAbsoluteUri("/revbendorderhub"))

               .WithAutomaticReconnect()

               .Build();

           

           _hubConnection.On<AXOrderHeader>("ReceiveMessage", (orderHeader) =>

           {

               int index = this._messages.FindIndex(x => x.OrderDid == orderHeader.OrderDid);

               if (index >= 0)

               {

                   if (orderHeader.OpenOrder)

                   {

                       this._messages[index] = orderHeader;

                   }

                   else

                   {

                       this._messages.RemoveAt(index);

                   }

               }

               else if (orderHeader.OpenOrder)

               {

                   this._messages.Add(orderHeader);

               }

               

               StateHasChanged();

           });

           

           await _hubConnection.StartAsync(); **<--- Call to intialise hub**

           loadCompleted = true;

       }

The module that it is failing in is the inbuilt HubConnection class at this point:

   private async Task StartAsyncInner(CancellationToken cancellationToken = default)

       {
           await _state.WaitConnectionLockAsync(token: cancellationToken).ConfigureAwait(false);

           try
           {
               if (!_state.TryChangeState(HubConnectionState.Disconnected, HubConnectionState.Connecting))
               {
                   throw new InvalidOperationException($"The {nameof(HubConnection)} cannot be started if it is not in the {nameof(HubConnectionState.Disconnected)} state.");
               }

               // The StopCts is canceled at the start of StopAsync should be reset every time the connection finishes stopping.

               // If this token is currently canceled, it means that StartAsync was called while StopAsync was still running.

               if (_state.StopCts.Token.IsCancellationRequested)
               {
                   throw new InvalidOperationException($"The {nameof(HubConnection)} cannot be started while {nameof(StopAsync)} is running.");
               }

               using (CancellationTokenUtils.CreateLinkedToken(cancellationToken, _state.StopCts.Token, out var linkedToken))
               {
                   await StartAsyncCore(linkedToken).ConfigureAwait(false); <-- **here is where it is failing**
               }   

               _state.ChangeState(HubConnectionState.Connecting, HubConnectionState.Connected);

           }
           catch
           {
               if (_state.TryChangeState(HubConnectionState.Connecting, HubConnectionState.Disconnected))
               {
                   _state.StopCts = new CancellationTokenSource();
               }
               throw;
           }
           finally
           {
               _state.ReleaseConnectionLock();
           }
       }

Regards

Peter

  • 0

    If hosting in Azure, do you have Web Sockets turned on in the AppService > Configuration > General Settings ?

    Posted 1 year ago by selliott
  • 0

    Hi,

      No it is not hosted, I am still in dev mode.

     

    Regards

    Peter

    Posted 1 year ago by buda56
  • 0

    It's difficult to say based on the provided information. What's on line 75 of RevbendOrderListViewPage.cs? Have you mapped to the hub in the Startup.cs or Program.cs file? I recommend reading through https://learn.microsoft.com/en-us/aspnet/core/signalr/hubs?view=aspnetcore-7.0 to see if you notice anything you've missed. If you're setting things up in the Startup.cs file, the example on that page may look something more like:

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapHub<ChatHub>("/Chat");
    }    
    Posted 1 year ago by selliott
  • 0

    Hi,

       Thanks for the response, yes the hub is mapped in the startup file..

                app.UseEndpoints(endpoints =>

                {

                    endpoints.MapDefaultControllerRoute();

                    endpoints.MapControllers();

                    endpoints.MapBlazorHub();

                    endpoints.MapFallbackToPage("/_Index");

                    // new SignalR endpoint routing setup

                    endpoints.MapHub<Hubs.ChatHub>(Constants.HubPaths.Chat);

                    endpoints.MapHub<Hubs.RevbendOrderHub>(Constants.HubPaths.RBOrders);

                });

    I am using the Blazor Boilerplate template from https://github.com/enkodellc which works a bit differently in that you don't directly call the hub it goes through a client which then created and interacts with the hub. I have tried duplicating this process in my hub but it fails as per my initial post.

     

    Regards

    Peter

    Posted 1 year ago by buda56
  • 0

    It's probably worth enabling detailed errors to see if that gives you more helpful information.

     builder.Services.AddSignalR(hubOptions =>
     {
        if (Environment.IsDevelopment()) {
            hubOptions.EnableDetailedErrors = true;
        }
     });

    It may make no difference, but I'd try initializing the hub right after you instantiate the HubConnectionBuilder, before _hubConnection.On...

    Posted 1 year ago by selliott Edited 1 year ago
  • 0

    Hi,

       Thanks for the quick reply, I have added the "detailed errors" section to SignalR and will try it again. I think it is already initialised??

        public OrderSyncClient(HttpClient httpClient, List<AXOrderHeader> messages)

        {

            _messages = messages;

            _connection = new HubConnectionBuilder()

                .WithUrl(new Uri(httpClient.BaseAddress, "revbendorderhub"), options =>

                {

                    foreach (var header in httpClient.DefaultRequestHeaders)

                        if (header.Key == "Cookie")

                            options.Headers.Add(header.Key, header.Value.First());

                })

                .WithAutomaticReconnect()

                .Build();

        }

     

    Regards

    Peter

    Posted 1 year ago by buda56
  • 0

    Ok it is now throwing this error??

    'RemoteNavigationManager' has not been initialized.

       at Microsoft.AspNetCore.Components.NavigationManager.AssertInitialized()

      at Microsoft.AspNetCore.Components.NavigationManager.get_BaseUri()

      at RevIntra.Server.Startup.<>c__DisplayClass7_0.<ConfigureServices>b__24(IServiceProvider s) in D:\Shared\Source\Repos\Revroof\RevIntra_BP - Test\RevIntra\Server\RevIntra.Server\Startup.cs:line 651

      at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)

      at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)

      at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)

      at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)

      at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)

      at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)

      at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)

      at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)

      at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass2_0.<RealizeService>b__0(ServiceProviderEngineScope scope)

      at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)

      at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)

      at Microsoft.AspNetCore.SignalR.Internal.DefaultHubActivator`1.Create()

      at Microsoft.AspNetCore.SignalR.Internal.DefaultHubDispatcher`1.<OnConnectedAsync>d__9.MoveNext()

     

    In my project startup file when I select the menu option that initaites the hub.

     

    Regards

    Peter

    Posted 1 year ago by buda56
  • 0

    The above error showsw when the connection tries to start (see code below)

        public async Task Start()

        {

            _connection.On<AXOrderHeader>("ReceiveMessage", (orderHeader) =>

            {

                int index = this._messages.FindIndex(x => x.OrderDid == orderHeader.OrderDid);

                if (index >= 0)

                {

                    if (orderHeader.OpenOrder)

                    {

                        this._messages[index] = orderHeader;

                    }

                    else

                    {

                        this._messages.RemoveAt(index);

                    }                

                }

                else if (orderHeader.OpenOrder)

                {

                    this._messages.Add(orderHeader);

                }

            });

           

            await _connection.StartAsync(); //<--- Error thrown here

        }

     

    Regards

    Peter

    Posted 1 year ago by buda56
  • 0

    I mean try moving _hubConnection.StartAsync() in OnInitializedAsync so it's more like this

    _hubConnection = new HubConnectionBuilder()
       .WithUrl(NavigationManager.ToAbsoluteUri("/revbendorderhub"))
       .WithAutomaticReconnect()
       .Build();
       
    await _hubConnection.StartAsync();
    
    _hubConnection.On<AXOrderHeader>("ReceiveMessage", (orderHeader) =>
    {
    	...
    });
    Posted 1 year ago by selliott
  • 0

    Hi,

      Thanks for the update. I have modified my code from using httpclient to using the navigationManager and moved the code from the startasync method. The hub now starts and connects with no errors, so.. so far so good, I will need to wire up the data collection and then confirm that it updates on screen.

        public OrderSyncClient(List<AXOrderHeader> messages, NavigationManager navigationManager)

        {

            _messages = messages;

            _navigationManager = navigationManager;

            _connection = new HubConnectionBuilder()

                .WithUrl(_navigationManager.ToAbsoluteUri("/revbendorderhub"))

                .WithAutomaticReconnect()

                .Build();

            _connection.StartAsync();

            _connection.On<AXOrderHeader>("ReceiveMessage", (orderHeader) =>

            {

                int index = this._messages.FindIndex(x => x.OrderDid == orderHeader.OrderDid);

                if (index >= 0)

                {

                    if (orderHeader.OpenOrder)

                    {

                        this._messages[index] = orderHeader;

                    }

                    else

                    {

                        this._messages.RemoveAt(index);

                    }

                }

                else if (orderHeader.OpenOrder)

                {

                    this._messages.Add(orderHeader);

                }

            });

        }

    Thanks for your help in getting this far.

    Regards

    Peter

    Posted 1 year ago by buda56
Someone is typing...

Post a Reply

You must be logged in to add a new post.
Number of online users: 0
An error has occurred. This application may no longer respond until reloaded. Reload 🗙