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

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

Patricia Arquette
Patricia ArquetteOriginal
2025-01-04 09:13:34879browse

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

Call SignalR Core Hub Method from Controller

In ASP.NET Core applications, it is often necessary to communicate with SignalR hubs from controllers to update client-side applications with server-side events. Here are two approaches to achieve this:

Solution 1: Using Untyped HubContext

This method allows you to directly invoke methods on all connected clients. Inject the untyped IHubContext into your controller:

public class VarDesignCommController : Controller
{
    private readonly IHubContext<VarDesignHub> _hubContext;

    public VarDesignCommController(IHubContext<VarDesignHub> hubContext)
    {
        _hubContext = hubContext;
    }

    [HttpPut("ProcessVarDesignCommResponse/{id}")]
    public async Task<IActionResult> ProcessVarDesignCommResponse(int id)
    {
        await _hubContext.Clients.All.InvokeAsync("TaskCompleted", id);

        return new JsonResult(true);
    }
}

Solution 2: Using Typed Hubs and Interfaces

This approach uses typed hubs and interfaces to define client-side methods that can be called from the controller.

Create an interface for the hub client:

public interface ITypedHubClient
{
    Task TaskCompleted(int id);
}

Inherit from Hub with the typed client interface:

public class VarDesignHub : Hub<ITypedHubClient>
{
    public async Task TaskCompleted(int id)
    {
        await Clients.All.InvokeAsync("Completed", id);
    }
}

Inject the typed hub context into the controller:

public class VarDesignCommController : Controller
{
    private readonly IHubContext<VarDesignHub, ITypedHubClient> _hubContext;

    public VarDesignCommController(IHubContext<VarDesignHub, ITypedHubClient> hubContext)
    {
        _hubContext = hubContext;
    }

    [HttpPut("ProcessVarDesignCommResponse/{id}")]
    public async Task<IActionResult> ProcessVarDesignCommResponse(int id)
    {
        await _hubContext.Clients.All.TaskCompleted(id);

        return new JsonResult(true);
    }
}

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

Statement:
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