Search code examples
c#asp.netasp.net-mvcsignalrsignalr-hub

SignalR hub Context.ConnectionId object reference error


I went through a bunch of tutorials for SignalR and sending messages to a specific client. I am getting the following:

Error:

An object reference is required for the non-static field, method, or property 'HubBase.Context'

Code:

public class ProgressHub : Hub
{

    public string msg = "Initializing and Preparing...";
    public int counter = 1;

    public static void SendMessage(string msg, int count)
    {
        var message = msg;
        var hubContext = GlobalHost.ConnectionManager.GetHubContext<ProgressHub>();
        //Context.ConnectionId throwing error
        hubContext.Clients.Client(Context.ConnectionId).sendMessage(string.Format(message), count); 
    }

    public void GetCountAndMessage()
    {
        Clients.Caller.sendMessage(string.Format(msg), counter);
    }
}

Not sure what I am doing wrong the line Context.connectionId is the exact same line they use yet mine is giving an object reference error?


Solution

  • As the error message states, you are trying to access the non-static Context property in your static method, which is not possible (see Static Classes and Static Class Members for further information). An option to resolve this issue would be making the SendMessage method non-static by removing the static keyword.