Click here to Skip to main content
15,886,063 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi!

I am trying to make simple chat app with signalR.

I did signalR part and have working chat. Now i want to save chat messages to database.
In order to save message i need to know id of current authentificated user but I found out that signalR hub doesnt support HttpContext.


Is there any workaround i could do to get value of HttpContext inside of signalR hub?

What I have tried:

I created separate controller that has function which submits message to db.
That function is called inside of chathub task but httpContext gives NullReference exception

here is controller function
C#
public void SpremiPoruku(string Poruka)
       {
           Poruka nova = new Poruka();
           User aktivan = Autenfikacija.GetLogiraniKorisnik(HttpContext);
           nova.Sadrzaj = Poruka;
           nova.VrijemeSlanja = DateTime.Now;
           nova.PosijateljID = aktivan.UserID;
           nova.ChatID = 3;

           db.Poruka.Add(nova);
           db.SaveChanges();
       }


and here is hub task
C#
public Task SendMessageToAll(string message)
        {

            ChatController chat = new ChatController(db);

            chat.SpremiPoruku(message);
            

            return Clients.All.SendAsync("PrimljenaPoruka", message);
        }

Sorry for non english code!!!

Thanks for trying to help!!!
Posted
Updated 20-Nov-20 2:03am

1 solution

The Hub class[^] has a Context property[^] which returns the HubCallerContext[^].

You can get the authenticated user by looking at the HubCallerContext.User property[^].
 
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