SignalR 将 IProgress<T> 从 js 客户端传递到集线器

SignalR pass IProgress<T> from js client to hub

是否可以将 IProgress<T> 从 js 客户端传递到 C# SignalR hub?我想做的是:

在集线器端:

public class ProgressHub : Hub<IProgressHub>
{
    public async Task Foo(string jobId, IProgress<int> progress)
    {
        Console.WriteLine($"Started monitoring {jobId}");

        for (int i = 0; i < 100; i++)
        {
            await Task.Delay(TimeSpan.FromSeconds(1)); // Simulate some work
            progress.Report(i);            
        }        
    }
}

public interface IProgressHub
{
    Task Foo(string jobId, Progress<int> progress);
}

js端:

connection
    .invoke("Foo", "this-is-job-id", progressPercentage => console.log(`Processed ${value}%`))
    .then(() => console.log("Processing done"));

signalr hub 上的方法被调用,但 IProgress 总是以 null 结束。

我刚在 Differences between ASP.NET SignalR and ASP.NET Core SignalR

中找到答案

The ability to pass arbitrary state between clients and the hub (often called HubState) has been removed, as well as support for progress messages. There is no counterpart of hub proxies at the moment.

最后我决定执行以下操作:

在集线器端:RegisterToProgress([...]) 将在内部调用 SendProgress([...]) 向客户端发送消息。

在 js 客户端:调用 RegisterToProgress 并收听 SendProgress 消息。