Connection ID required SignalR Asp.net core Web api

Vuyiswa Maseko 351 Reputation points
2023-01-01T23:19:10.33+00:00

Good Day Everyone

i have created a Asp.net Core web api for the purpose of SignalR

my hub is defined like this

 public class ChatHub : Hub  
{  
    public ChatHub()  
    {  
    }  
    public void SendMessage(string AUTHOR, string CHAT_MESSAGE, string model)  
    {  
        try  
        {   
  
            CHAT_MESSAGES_Model chanmessagemodel = Newtonsoft.Json.JsonConvert.DeserializeObject<CHAT_MESSAGES_Model>(model);   
               
            Clients.All.SendAsync("ReceiveMessage",AUTHOR, chanmessagemodel.CHAT_MESSAGE, model);   
        }  
        catch (Exception ex)  
        {  
             //  
        }  
    }  
   
    public async Task SendMessageAsync( string AUTHOR, string CHAT_MESSAGE, string model)  
    {  
        try  
        {  
            CHAT_MESSAGES_Model chanmessagemodel = Newtonsoft.Json.JsonConvert.DeserializeObject<CHAT_MESSAGES_Model>(model);  
  
            await Clients.All.SendAsync("ReceiveMessage",AUTHOR, chanmessagemodel.CHAT_MESSAGE, model);  
  
        }  
        catch (Exception ex)  
        {  
           //  
        }  
    }  
}  

 

and Program.cs looks like this

 var builder = WebApplication.CreateBuilder(args);  
  
// Add services to the container.  
  
builder.Services.AddControllers();  
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle  
builder.Services.AddEndpointsApiExplorer();  
builder.Services.AddSwaggerGen();  
  
//services cors  
builder.Services.AddCors(p => p.AddPolicy("corsapp", builder =>  
{  
    builder.WithOrigins("*").AllowAnyMethod().AllowAnyHeader();  
}));  
  
  
builder.Services.AddSignalR();  
  
  
builder.Services.AddResponseCompression(opts =>  
{  
    opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(new[] { "application/octet-stream" });  
});  
   
var app = builder.Build();  
  
app.UseRouting();  
  
//app cors  
app.UseCors("corsapp");  
  
  
  
// Configure the HTTP request pipeline.  
if (app.Environment.IsDevelopment())  
{  
    app.UseSwagger();  
    app.UseSwaggerUI();  
}  
     
app.UseHttpsRedirection();  
  
app.UseAuthorization();  
  
app.MapControllers();  
  
app.MapHub<ChatHub>("/chat");  
    
app.Run();  

when i access the local host or the hosted URL (https://localhost:7054/chat
) for testing purposes , i get this error

Connection ID required

In using this in Xamarin like this

 string serverurl = "https://myserver.com/SignalRChat";  
  
       hubConnection = new HubConnectionBuilder()  
                 .WithUrl($"{serverurl}/chatHub")  
                 .Build();  
  
   await hubConnection.StartAsync();  

 Receiving the message  

   hubConnection.On<string, string,string>("ReceiveMessage", (AUTHOR, MESSAGE, Model) =>  
        {  
            //Do work   
        });  

and i get an error

Response status code does not indicate success: 404 (Not Found).  

The error happens on this line

 await hubConnection.StartAsync();  

What could be the issue ?

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,292 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,148 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,248 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,011 Reputation points Microsoft Vendor
    2023-01-02T02:59:40.873+00:00

    Hi @Vuyiswa Maseko ,

    when i access the local host or the hosted URL (https://localhost:7054/chat
    ) for testing purposes , i get this error

    Connection ID required

    What could be the issue ?

    As we all known, in asp.net core SignalR, to send messages between clients and server, we need to build the connection first and then calling the hub method or client method to send messages. But, if you directly access the chat hub, the SignalR connection isn't connected, so it doesn't have the connection ID and will show this error.

    To solve this issue, you can create a web page(html/cshtml page) and refer to the following JavaScript to builder the SignalR Connection and create a JavaScript client:

    275296-image.png

    Then, access the web page (html/cshtml) page to send or receive the messages. More detail information, see Get started with ASP.NET Core SignalR.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments

3 additional answers

Sort by: Most helpful
  1. SurferOnWww 1,906 Reputation points
    2023-01-02T01:04:19.9+00:00

    Can the following stackoverflow thread help?

    Connection ID required
    https://stackoverflow.com/questions/47919678/connection-id-required

    "The problem was that I have configured the hub at route /chat while my ChatController was also responsible for it."


  2. Vuyiswa Maseko 351 Reputation points
    2023-01-02T06:38:31.56+00:00

    hi @Zhi Lv - MSFT

    sorry i did not add the part on how i consume this service. after that i use Xamarin to access it like this

    In using this in Xamarin like this

    string serverurl = "https://myserver.com/SignalRChat";

       hubConnection = new HubConnectionBuilder()  
                 .WithUrl($"{serverurl}/chatHub")  
                 .Build();  
    

    await hubConnection.StartAsync();

    Receiving the message

       hubConnection.On<string, string,string>("ReceiveMessage", (AUTHOR, MESSAGE, Model) =>  
            {  
                //Do work   
            });  
    

    and i get an error

    Response status code does not indicate success: 404 (Not Found).


  3. Vuyiswa Maseko 351 Reputation points
    2023-01-04T10:41:39.39+00:00

    Good Day @Zhilz-MSFT

    you have steered me to the right direction, all is working now . this is what i did

    initialization looks like this

      hubConnection  = new HubConnectionBuilder()  
                              .WithUrl($"{serverurl}/chat")  
                              .Build();  
      
                    await hubConnection.StartAsync();  
    

    and when i send the message its like this

            string json = JsonConvert.SerializeObject(model);    
            await hubConnection.InvokeAsync("SendMessage", GenericMethods.USER_DATA.USER_HANDLE, model.CHAT_MESSAGE, json);  
          
    

    And it works nicely.

    0 comments No comments