Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abort / Stop SignalR connection from server with a message and status code

I'm creating a SignalR server and I added a couple of rules that the clients should follow when they want to connect to server.

The rules (also call them 'validators') are, for example, that a certain header should be present when the client request to connect.

My question is: how can "reject" a connection with a proper "status code" and "message" and kick out the user? I didn't find any helpful thread around.

Thanks for reading.

like image 657
brian enno Avatar asked Oct 19 '25 10:10

brian enno


1 Answers

I Checked the hub class and found:

enter image description here and if the connection is assciated with httprequest,you could use Context.GetHttpContext() method to get the httpcontext, So I tried as below:

public override async Task OnConnectedAsync()
        {
            var errormessage = "the connection was disconnected due to Some reason";
            var header = Context.GetHttpContext().Request.Headers;
            if (header.ContainsKey("Origin"))
            {
                await Clients.Caller.SendAsync("Disconnect", errormessage);
                Context.Abort();
                .......                
            }
            
        }

The Result: enter image description here enter image description here

like image 130
Ruikai Feng Avatar answered Oct 21 '25 12:10

Ruikai Feng