一旦我创建了一个派生自Microsoft.AspNetCore.SignalR.Hub<IChatClient> 的ChatHub。
所有组件都位于单独的 .net 标准库中。
IChatClient 看起来像(用于类型安全):
public interface IChatClient
{
Task ReceiveChatMessage(string user, string message, DateTime sentAt, bool isMarkedAsImportant);
Task ReceiveChatActivity(string user, Activity activity, DateTime sentAt);
}
最后我在一个 ASP.net 核心项目中使用了 ChatHub,其中集线器在 Startup 中配置,如下所示:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseCors(builder =>
{
builder.WithOrigins("https://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
IdentityModelEventSource.ShowPII = true;
}
else
{
app.UseGlobalExceptionHandler();
app.UseHttpsRedirection();
app.NwebSecApiSetup();
}
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<ChatHub>("/api/chat");
endpoints.MapHub<EventHub>("/api/events");
});
}
此外,我在 ConfigureServices 方法中为 SignalR 配置了更多内容:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers().AddControllersAsServices();
services.AddHttpContextAccessor();
services.AddConnections();
services.AddSignalR(options =>
{
options.EnableDetailedErrors = true;
})
.AddNewtonsoftJsonProtocol();
...
}
我想您也可以在其他项目中轻松使用此类 Hub。