Search code examples
.net-coreasp.net-core-webapisignalr-hubasp.net-core-signalr

Calling Web-Api from a SignalR Hub


I am creating a WebApi server with integrated SignalR Hubs. For simplicity's sake I am using a Controller which is operating on a List.

  [Route("api/[controller]")]
  [ApiController]
  public class ValuesController : ControllerBase
  {

    public static List<string> Source { get; set; } = new List<string>();
    public static int counter = 0;

    private IHubContext<ValuesHub, IValuesClient> hubContext;

    public ValuesController(IHubContext<ValuesHub, IValuesClient> hub)
    {
      Source.Add("bla" + counter);
      counter++;
      Source.Add("bla" + counter);
      counter++;
      this.hubContext = hub;
    }

    // GET api/values
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
      return Source;
    }

    // GET api/values/x
    [HttpGet("{id}")]
    public ActionResult<string> Get(int id)
    {
      return Source[id];
    }

    // POST api/values
    [HttpPost]
    public void Post([FromBody] string value)
    {
      Source.Add(value);
    }

    // PUT api/values/x
    [HttpPut("{id}")]
    public void Put(int id, [FromBody] string value)
    {
      Source[id] = value;
    }

    // DELETE api/values/x
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
      var item = Source[id];
      Source.Remove(item);
      Console.WriteLine("Outgoing message!");
      hubContext.Clients.All.ReceiveMessage("Message incoming", "Blaaaaa");
    }
  }
}

My Hub doesn't do anything special yet:

  public interface IValuesClient
  {
    Task ReceiveMessage(string value, string message);
    Task ReceiveMessage(string message);
  }

  public class ValuesHub : Hub<IValuesClient>
  {

    // private static ValuesController ctrl = Glo

    public override async Task OnConnectedAsync()
    {
      await Groups.AddToGroupAsync(Context.ConnectionId, "Users");
      Console.WriteLine("Client connected - Client-Id: {0}", Context.ConnectionId);
      await base.OnConnectedAsync();
    }

    public override async Task OnDisconnectedAsync(Exception exception)
    {
      await Groups.RemoveFromGroupAsync(Context.ConnectionId, "Users");
      Console.WriteLine("Client disconnected - Client-Id: {0}", Context.ConnectionId);
      Console.WriteLine("Disconnection due to: {0}", exception);
      await base.OnDisconnectedAsync(exception);
    }

    public async Task MessageToAll(string user, string message)
    {
      Console.WriteLine("SendMessage - User: {0} - Message: {1}", user, message);
      await Clients.All.ReceiveMessage(user, message);
    }

    public async Task MessageToCaller(string message)
    {
      Console.WriteLine("SendMessageToCaller: {0}", message);
      await Clients.Caller.ReceiveMessage(message);
    }
  }
}

Also for simplicity's sake I will not go into detail why I want to achieve this, but I want the server to wait for a certain amount of time and then delete the according value, after a disconnection is detected. Let's say I want to simply delete the first element in my Source list.

How would I access the according Controller-functions from inside my OnDisconnectedAsync function?

One idea I came up with is to create a HttpClient inside my Hub and let the Hub act as a client here by calling e. g. DELETE: http://localhost:5000/api/values/0. I have to admit this sounds like a rather horrible approach, though.


Solution

  • So If I understand your problem is that you are having is that you want to access the methods on the controller from your hubs?

    If this is the case - It seems to me that you have a fundamental design flaw. I would create a service that handles all the things your controller is doing, and then inject this service directly into the hub. Then you can use that service directly in the hub on the overrides and operate on your list . If this is unclear I can Provide an example.

       public class ValuesHub : Hub<IValuesClient>
        {
       IListService _listService; 
     public ValuesHub (IListService listService)
        {
            _listService = listService;
        }
    
    public override async Task OnConnectedAsync()
    {
      await Groups.AddToGroupAsync(Context.ConnectionId, "Users");
      Console.WriteLine("Client connected - Client-Id: {0}", Context.ConnectionId);
      await base.OnConnectedAsync();
    }
    
    public override async Task OnDisconnectedAsync(Exception exception)
    {
      await Groups.RemoveFromGroupAsync(Context.ConnectionId, "Users");
      Console.WriteLine("Client disconnected - Client-Id: {0}", Context.ConnectionId);
      Console.WriteLine("Disconnection due to: {0}", exception);
       //Call your methods here.
      _listService.RemoveFirstElement();
      await base.OnDisconnectedAsync(exception);
    }
    
    public async Task MessageToAll(string user, string message)
    {
      Console.WriteLine("SendMessage - User: {0} - Message: {1}", user, message);
      await Clients.All.ReceiveMessage(user, message);
    }
    
    public async Task MessageToCaller(string message)
    {
      Console.WriteLine("SendMessageToCaller: {0}", message);
      await Clients.Caller.ReceiveMessage(message);
    }
       }
     }
    

    Thats your hub - See service example below

      public class ListService : IListService
       {
        public void RemoveFirstElement()
        {
            //Delete Your Element here
        }
    }
    
    public interface IListService
    {
        void RemoveFirstElement();
    }
    

    And then your startup.cs

     services.AddSingleton<IListService,ListService>();