Error encountered: Negotiation with the server was unsuccessful, resulting in an error message stating "Not Found."

I'm currently working on a project using SignalR with ASP.NET Boilerplate .NET Core 3.1, but I've run into an issue.

Error: Negotiation failed with the server: Error: Not Found

Is there a way to resolve this problem without skipping negotiation? (Solution mentioned here)

zone-evergreen.js:2845 POST http://localhost:21021/signalr/negotiate?enc_auth_token=wNYmO41%2F Show 162 more frames signalr.min.js:16 [2020-06-07T10:17:31.634Z] Error: Connection initiation failed: Error: Not Found

Below is the Angular Code:

  
ngOnInit(): void {
    this.renderer.addClass(document.body, 'sidebar-mini');

     // Commenting out old initialization and replacing it with new one
     SignalRAspNetCoreHelper.initSignalR(() => {
      var chatHub = null;

      abp.signalr.startConnection(abp.appPath + 'signalr-myChatHub', function (connection) {
          chatHub = connection; 

          connection.on('getMessage', function (message) { 
              console.log('received message: ' + message);
          });
      }).then(function (connection) {
          abp.log.debug('Connected to myChatHub server!');
          abp.event.trigger('myChatHub.connected');
      });

      abp.event.on('myChatHub.connected', function() { 
          chatHub.invoke('sendMessage', "Hi everybody, I'm connected to the chat!"); 
      });
  });
}

Here is the .NET Core Class code :

using Abp.Dependency;
using Abp.Runtime.Session;
using Castle.Core.Logging;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace HealthMapControlPanel.ChatAppService
{
   public class MyChatHub : Hub, ITransientDependency
    {
        public IAbpSession AbpSession { get; set; }

        public ILogger Logger { get; set; }

        public MyChatHub()
        {
            AbpSession = NullAbpSession.Instance;
            Logger = NullLogger.Instance;
        }

        public async Task SendMessage(string message)
        {
            await Clients.All.SendAsync("getMessage", string.Format("User {0}: {1}", AbpSession.UserId, message));
        }

        public override async Task OnConnectedAsync()
        {
            await base.OnConnectedAsync();
            Logger.Debug("A client connected to MyChatHub: " + Context.ConnectionId);
        }

        public override async Task OnDisconnectedAsync(Exception exception)
        {
            await base.OnDisconnectedAsync(exception);
            Logger.Debug("A client disconnected from MyChatHub: " + Context.ConnectionId);
        }
    }
}

Related code in Startup.cs class:

public void Configure(IApplicationBuilder app,  ILoggerFactory loggerFactory)
{
  app.UseSignalR(routes =>
            {
                routes.MapHub<MyChatHub>("/signalr-myChatHub");
            });

 app.UseEndpoints(endpoints =>
            {
                endpoints.MapHub<MyChatHub>("/signalr-myChatHub");
                endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapControllerRoute("defaultWithArea", "{area}/{controller=Home}/{action=Index}/{id?}");
            });
}

Also here is the screenshot of Web Browser Console:

https://i.sstatic.net/eebSe.png

Answer №1

When encountering the error related to connecting to /signalr for AbpCommonHub, it is essential for real-time notifications as part of ABP.
For more information, refer to the ABP documentation:

To resolve this issue, ensure that you restore

endpoints.MapHub<AbpCommonHub>("/signalr");
.

app.UseEndpoints(endpoints =>
{
    endpoints.MapHub<AbpCommonHub>("/signalr"); // Make sure to include this
    endpoints.MapHub<MyChatHub>("/signalr-myChatHub");
    endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
    endpoints.MapControllerRoute("defaultWithArea", "{area}/{controller=Home}/{action=Index}/{id?}");
});

Additionally, consider removing app.UseSignalR(...);, as it has been deprecated in favor of app.UseEndpoints(...);.

Answer №2

According to the latest documentation, it is no longer necessary/deprecated to use UseEndPoints. You can now directly map the endpoint onto the web api.

app.UseEndpoints(endpoints =>
{
    endpoints.MapHub<AbpCommonHub>("/signalr"); // Restore this
    endpoints.MapHub<MyChatHub>("/signalr-myChatHub");
    endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
    endpoints.MapControllerRoute("defaultWithArea", "{area}/{controller=Home}/{action=Index}/{id?}");
});

Now you can simply do:

app.MapHub<AbpCommonHub>("/signalr"); 
app.MapHub<MyChatHub>("/signalr-myChatHub");

Link for more information

Answer №3

Ensure that you have correctly spelled the hub endpoint string on both the client-side and server-side. For instance, if your backend associates your hub with /notificationsHub:

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapHub<NotificationsHub>("/notificationsHub");
        });

It is important that the frontend endpoint string matches exactly:

        this.notificationHubConnection = new signalR.HubConnectionBuilder()
          .withUrl(environment.apiHost + '/notificationsHub')
          .withAutomaticReconnect()
          .build();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the possibilities of integrating jQuery into Angular 2 using Javascript

import {Component, ElementRef, OnInit} from 'angular2/core'; declare var jQuery:any; @Component({ selector: 'jquery-integration', templateUrl: './components/jquery-integration/jquery-integration.html' } ...

Extend an array by Parsing JSON

I'm struggling to retrieve the JSON string from localStorage and add a new dish to it. It's not functioning correctly, can anyone lend me a hand? I am utilizing TypeScript. interface Dish { id: number; name: string; desc: string; ...

How do AppComponent and @Component relate to each other in AngularJs 2?

Recently, I came across the file app.component.ts in Example and found some interesting code. The link to the example is: here. Here's a snippet of the code: import { Component } from '@angular/core'; export class Hero { id: number; na ...

How should I proceed if a TypeScript definition file that I am relying on is lacking a specific definition?

I have encountered an issue while using the React type definitions for my project. The focus method is missing on elements in the array returned by the refs property, which prevents me from getting a specific example to work. The compiler error states: pro ...

Mastering Typescript lookup types - effectively limit the properties included in a merge operation with the Partial type

Exploring lookup types, I'm interested in creating a safe-merge utility function that can update an entity of type T with a subset of keys from another object. The objective is to leverage the TypeScript compiler to catch any misspelled properties or ...

Issue with normalizing UV coordinates to a range of 0 and 1 in threejs

I am facing an issue where my model has UV coordinates that are outside the range of 0 and 1. I have attempted to normalize these coordinates with a function, but the results are not as expected. This is the function I am using to convert the UV coordinate ...

Developing a dynamic web application using Asp.Net Core integrated with React and material

After setting up an Asp.Net Core project using the react template, I decided to incorporate material-ui by following the steps outlined on this page. However, encountered some dependency issues along the way. To resolve them, I had to update the react and ...

Warning: TypeScript linter alert - the no-unused-variable rule is now outdated; however, I do not have this configuration enabled

After 3 long months, I came across a warning in a project that was being refreshed today. The warning says "no-unused-variable is deprecated. Since TypeScript 2.9. Please use the built-in compiler checks instead." Oddly enough, my tsconfig.json file do ...

Error: The method isEqual for the book object is undefined

Why is the 'book.isEqual' method of the Book class not recognized as a function when called in the BooksService class? In file: models/book.model.ts export class Book { constructor(public title: string, public author: string) { } i ...

Upon running the code, no errors appear on the console. However, my project isn't functioning properly and I'm encountering errors on the web console

ReferenceError: require is not defined when trying to access external "url" at Object.url in webpack_require (bootstrap:83) at client:6 importing from webpack-dev-server client index.js(http://0.0.0.0:0) vendor.js:219506 dynamically imp ...

Using DefinitelyTyped in a forked library: A step-by-step guide

Recently, I found myself in a situation where I had to fork libA just to update one of its dependencies. It was frustrating to discover that LibA did not come with typescript definitions on its own, although it did have an entry in DefinitelyTyped. Now th ...

Utilizing Typescript Decorators to dynamically assign instance fields within a class for internal use

I am interested in delving into Typescript Decorators to enhance my coding skills. My primary objective is to emulate the functionality of @Slf4J from Project Lombok in Java using Typescript. The concept involves annotating/decorating a class with somethin ...

Prevent Gatsby from compiling when encountering a TypeScript error

When working on my CRA TypeScript projects, I appreciate how TypeScript prevents the dev server from compiling whenever there's an error in my code. Instead, it displays the error in both the browser and console, which helps me quickly identify and fi ...

Having trouble with gsap.reverse() not functioning properly when using onMouseLeave event in React

I've been incorporating simple gsap animations into my React application. I have successfully triggered an animation.play() function on onMouseEnter, but for some reason, the animation.reverse() function is not functioning as expected. Here's ho ...

Unable to initialize metro server due to the error "attachToServer is not a valid function"

After following the instructions in the original documentation, I executed npx react-native init AwesomeProject without making any changes. However, when I try to run npx react-native start or yarn start, I encounter an error stating that attachToServer i ...

Angular issue: "anticipated to exit Angular zone, yet still found within"

I'm currently in the process of building a web application using Angular, and an error keeps appearing in the Chrome console: https://i.stack.imgur.com/sikuu.png Initially, I ignored the error as it didn't seem to impact the app's functiona ...

Strict mode enhances the security and reliability of map data structures

Utilizing strict mode in my code has led to an issue when trying to assign an object value from a Map. Despite the fact that the value obtained from the Map is not undefined, strict mode is throwing the error Type A[]|undefined isn't assignable to typ ...

Can child components forward specific events to their parent component?

I created a basic component that triggers events whenever a button is clicked. InnerComponent.vue <template> <v-btn @click="emit('something-happened')">Click me</v-btn> </template> <script setup lang=" ...

Exploring the latest upgrades in React 18 with a focus on TypeScript integration

I am currently working on a complex TypeScript project with React and recently made the decision to upgrade to the new version of React 18. After running the following commands: npm install react@18 npm install react-dom@18 npm install @types/react-dom@18 ...

Adjusting the ng-turnstile Dimensions

Looking for a way to adjust the width of CloudFlare Turnstile to match its parent container's layout without causing any issues with the Iframe. Is there a more efficient method to achieve this? The current solution I have seems to be messy: import { ...