Click here to Skip to main content
15,886,823 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi!
I am trying to make something like customer service chat with signalr.
I am able to use signalr to send message to every client but struggle with getting connectionID value anywhere outside of ChatHub so i could send to induvidual clients.

Here is my controller code
C#
public IActionResult PosaljiPoruku(PorukaVM model)
       {



           _hubContext.Clients.All.SendAsync("PrimljenaPoruka",model.Poruka );
           return PartialView("SubmitFormPartial");
       }


my js file

JavaScript
var connection = new signalR.HubConnectionBuilder()
    .withUrl("/chatt", {
        accessTokenFactory: () => "testing"
    })
    .build();

connection.on("PrimljenaPoruka", function (poruka) {

   //code for generating new message

   
});


connection.start().catch(function (err) {
    return console.error(err.toString());
});


and my hub code
C#
public class ChatHub : Hub
    {

        public string GetConnectionId()
        {
            return Context.ConnectionId;
        }

       

    }


What I have tried:

Tried some stuff that doesn't work like creating ChatHub instance in controller, accesing GetConnectionId() with ihubContext...

Saw somewhere that this code could be used to access connectionID on client side but not sure how to call it?

JavaScript
//connection.invoke('GetConnectionId')
//    .then(function (connectionId) {
//        // Send the connectionId to controller
//    });


I am really stuck on this for some time now any help is really appreciated!!!!!
Thanks for reading and trying to help!
Posted
Updated 24-Jan-21 14:17pm

Clearly you need to write the getconnectionid method, in order to take a value on your server, and share it with clients. Are you trying to create a group chat or connection? I am not sure you can just share an id and add someone to a session?
 
Share this answer
 
I solved it like this

JavaScript
connection.start().then(function () {
   connection.invoke('GetConnectionId')
   .then(function (connectionId) {
      //alert(connectionId);

   })
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900