.Net Core SignalR 无法在启动时添加或使用

.Net Core SignalR cannot add or use in startup

我最近回到了一个使用 SignalR 的旧 .Net Core 应用程序。

我认为当时唯一可用于 .Net Core 应用程序的 SignalR NuGet 包是预览版。它奏效了。

我现在在一台新机器上,不知道这个包的预览提要是什么,所以我卸载了它并安装了这个:

> Install-Package Microsoft.AspNet.SignalR.Core -Version 2.4.1

除了 Startup.cs 文件中的这两个错误之外,除了一些名称空间更改外,一切似乎都很好。

Error CS1061 'IServiceCollection' does not contain a definition for 'AddSignalR' and no accessible extension method 'AddSignalR' accepting a first argument of type 'IServiceCollection' could be found (are you missing a using directive or an assembly reference?)

Error CS1061 'IApplicationBuilder' does not contain a definition for 'UseSignalR' and no accessible extension method 'UseSignalR' accepting a first argument of type 'IApplicationBuilder' could be found (are you missing a using directive or an assembly reference?)

我环顾四周,除了有人建议您需要安装我找不到的 Microsoft.AspNetCore.SignalR.Http 之外,我没有太多可用的。其他人建议您需要安装这个:

Install-Package Microsoft.AspNetCore.SignalR.Client -Version 1.1.0

我已经尝试过,但错误仍然存​​在,如何让这些错误消失?

Microsoft.AspNetCore.SignalR 自 2.1 以来是 ASP.NET 核心的一部分。

因此,如果您在 Visual Studio 中的 Project->Properties->Target framework 下将目标版本设置为 NET Core 2.1 或更高版本,您应该可以在 [=12] 中调用 services.AddSignalR() =]方法。

我通过替换

中的代码解决了这个问题
app.UseSignalR(routes =>
        {
            routes.MapHub<NotifyHub>("notify"); 
        });

app.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<NotifyHub>("/notify");
        });

我正在使用 Dot net 5.0

正如@Farman 已经指出的那样,解决方案是使用.UseEndpoints()。正如 MSFT 所记录的,这是通过替换 .UseSignalR()

推荐的方法

推荐方法:

app.UseEndpoints(endpoints =>
{
    endpoints.MapHub<SomeHub>("/path");
});

.UseSignalR() 从 .NET Core 版本 3.0 开始过时,建议移动到 .UseEndpoints() 从 .NET Core 版本 3.1 开始。

可以找到更多信息AspNet Core Compatability

点网5.0

先添加包:

dotnet add package Microsoft.AspNet.SignalR.Core --version 2.4.1

中,public void ConfigureServices(IServiceCollection services)

services.AddSignalR();

中,public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

app.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<NotifyHub>("/notify");
        });