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
{
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);
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
2016-08-18 【转】C# 中的委托和事件
2016-08-18 你知道C#中的Lambda表达式的演化过程吗