Home > Backend Development > C++ > How to Call a SignalR Hub Method from an ASP.NET Core Controller?

How to Call a SignalR Hub Method from an ASP.NET Core Controller?

Susan Sarandon
Release: 2025-01-05 03:32:39
Original
861 people have browsed it

How to Call a SignalR Hub Method from an ASP.NET Core Controller?

Calling SignalR Core Hub Method from Controller

SignalR Core provides a powerful real-time communication mechanism for ASP.NET Core applications. This article addresses the common scenario of calling a SignalR hub method from a controller.

The provided example demonstrates the need to notify connected clients upon the completion of an external operation initiated from a Windows service. Since the service cannot directly interact with SignalR, we explore two potential solutions.

Solution 1: Using IHubContext

Inject the IHubContext for the desired hub into the controller:

public class VarDesignCommController : Controller
{
    public VarDesignCommController(IHubContext<VarDesignHub> hubcontext)
    {
        HubContext = hubcontext;
    }
    ...
}
Copy after login

Then invoke the hub method:

await this.HubContext.Clients.All.InvokeAsync("Completed", id);
Copy after login

Solution 2: Using Typed Hubs

For more granular control, create a typed client interface:

public interface ITypedHubClient
{
    Task BroadcastMessage(string name, string message);
}
Copy after login

Inherit from the Hub class and define the client-side method:

public class ChatHub : Hub<ITypedHubClient>
{
    public void Send(string name, string message)
    {
        Clients.All.BroadcastMessage(name, message);
    }
}
Copy after login

Inject the typed hub context and invoke the method:

// In VarDesignCommController
[Route("api/demo")]
public class DemoController : Controller
{
    IHubContext<ChatHub, ITypedHubClient> _chatHubContext;
    public DemoController(IHubContext<ChatHub, ITypedHubClient> chatHubContext)
    {
        _chatHubContext = chatHubContext;
    }
    
    [HttpGet]
    public IEnumerable<string> Get()
    {
        _chatHubContext.Clients.All.BroadcastMessage("test", "test");
        return new string[] { "value1", "value2" };
    }
}
Copy after login

The above is the detailed content of How to Call a SignalR Hub Method from an ASP.NET Core Controller?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template