SignalR 客户端源生成器 客户端强类型方法

发布时间 2023-08-18 10:35:04作者: WebEnh

 

SignalR 客户端源生成器根据您定义的接口生成强类型的发送和接收代码。您可以在客户端上重用来自强类型 SignalR 集线器的相同接口来代替松散类型的 .On("methodName", ...) 方法。同样,您的集线器可以为其方法实现一个接口,并且客户端可以使用该相同接口来调用集线器方法。

要使用 SignalR 客户端源生成器:

[AttributeUsage(AttributeTargets.Method)]
internal class HubServerProxyAttribute : Attribute
{
}

[AttributeUsage(AttributeTargets.Method)]
internal class HubClientProxyAttribute : Attribute
{
}
  • 为您的项目添加一个静态分部类,并使用 [HubClientProxy] 和 [HubServerProxy] 属性编写静态分部方法
internal static partial class MyCustomExtensions
{
    [HubClientProxy]
    public static partial IDisposable ClientRegistration<T>(this HubConnection connection, T provider);

    [HubServerProxy]
    public static partial T ServerProxy<T>(this HubConnection connection);
}
  • 使用代码中的部分方法!
public interface IServerHub
{
    Task SendMessage(string message);
    Task<int> Echo(int i);
}

public interface IClient
{
    Task ReceiveMessage(string message);
}

public class Client : IClient
{
    // Equivalent to HubConnection.On("ReceiveMessage", (message) => {});
    Task ReceiveMessage(string message)
    {
        return Task.CompletedTask;
    }
}

HubConnection connection = new HubConnectionBuilder().WithUrl("...").Build();
var stronglyTypedConnection = connection.ServerProxy<IServerHub>();
var registrations = connection.ClientRegistration<IClient>(new Client());

await stronglyTypedConnection.SendMessage("Hello world");
var echo = await stronglyTypedConnection.Echo(10);