调用SignalR Hub不适用于Asp.Net Core Web API - c#

我是SignalR的新手。我正在尝试设置一个Asp.Net Core WebAPI,以便其他客户端可以使用SignalR连接到它并获取实时数据。
我的Hub类是:

public class TimeHub : Hub
{
    public async Task UpdateTime(string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", message);
    }
}

我有一个中继课程,如下所示:

public class TimeRelay : ITimeRelay
{
    private readonly IHubContext<TimeHub> _timeHubContext;

    public TimeRelay(IHubContext<TimeHub> context)
    {

        _timeHubContext = context;
        Task.Factory.StartNew(async () =>
        {
            while (true)
            {
                await context.Clients.All.SendAsync("UpdateTime", DateTime.Now.ToShortDateString());
                Thread.Sleep(2000);
            }
        });
    }
}

启动类:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    services.AddSignalR();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseDeveloperExceptionPage();

    app.UseHttpsRedirection();

    app.UseSignalR((x) =>
    {
        x.MapHub<TimeHub>("/timeHub");
    });
    app.UseMvc();
}

客户端是一个控制台应用程序,代码为:

class Program
{    
    static Action<string> OnReceivedAction = OnReceived;

    static void Main(string[] args)
    {
        Connect();
        Console.ReadLine();
    }

    private static async void Connect()
    {
        var hubConnectionBuilder = new HubConnectionBuilder();

        var hubConnection = hubConnectionBuilder.WithUrl("http://localhost:60211/timeHub").Build();

        await hubConnection.StartAsync();

        var on = hubConnection.On("ReceiveMessage", OnReceivedAction);

        Console.ReadLine();    
        on.Dispose();
        await hubConnection.StopAsync();
    }

    static void OnReceived(string message)
    {
        System.Console.WriteLine($"{message}");
    }
}

我尝试调试该应用程序。客户端成功连接到TimeHub。客户端连接后,Clients.All中的连接数从0更改为1。但是,当执行await context.Clients.All.SendAsync("UpdateTime", DateTime.Now.ToShortDateString());时,UpdateTime中的TimeHub函数不会得到执行,并且客户端也不会收到任何消息。

我尝试在"UpdateTime"类的"SendMessage"中使用"ReceiveMessage"Clients.All.SendAsyncTimeRelay作为方法。没事。有人可以指出我的错误。

参考方案

对于Clients,如果没有客户端连接到服务器,则为null。为了同时启动Asp.Net Core SignalRConsole AppClients可以为null,因为在Console App连接signalR服务器之前可以调用Index

请尝试以下步骤:

更改TimeHub

public class TimeHub: Hub
{
public async Task UpdateTime(string message)
{
    if (Clients != null)
    {
        await Clients.All.SendAsync("ReceiveMessage", message);
    }
}
}

注册TimeHub

 services.AddSingleton<TimeHub>();  

控制者

 public class HomeController : Controller
{
private readonly TimeHub _timeHub;
public HomeController(TimeHub timeHub)
{
    _timeHub = timeHub;
}
public IActionResult Index()
{
    Task.Factory.StartNew(async () =>
    {
        while (true)
        {
            try
            {
                await _timeHub.UpdateTime(DateTime.Now.ToShortDateString());
                Thread.Sleep(2000);
            }
            catch (Exception ex)
            {

            }
        }
    });
    return View();
}

Visual Studio,ASP.Net(.Net Framework),并在项目中包含NuGet安装的软件包 - javascript

我在Visual Studio 2017中有一个主要由JavaScript组成的ASP.Net(.Net Framework)MVC Web应用程序。我已经使用NuGet安装了一个软件包(特别是marker-animate-unobtrusive软件包。)文档继续说我应该在我的HTML页面中包含JavaScript,但是在仔细检查了NuGet的内容后,我不确…

java.net.URI.create异常 - java

java.net.URI.create("http://adserver.adtech.de/adlink|3.0") 抛出java.net.URISyntaxException: Illegal character in path at index 32: http://adserver.adtech.de/adlink|3.0 虽然n…

在ASP.NET WebForms中在服务器端初始化bootsrap datatimepicker - javascript

我有这个HTML<div class='datepicker input-group date' id='datetimepickerStart'> <input type='text' class="form-control" /> <span c…

SQLite。修复sqlite-net-wp8项目依赖项 - c#

为什么SQLGet在NuGet上不可用?为什么它是Visual Studio的一部分,您必须在“工具”->“扩展和更新”中查找更新?在过去的几个月中,我开始对Windows 8和Windows Phone 8进行编码,我希望对此有所了解。对我来说,在Windows 8项目上使用SQLite会创建VS级依赖关系。假设我使用Visual Studio ID…

C#如何将System.Net.ConnectStream转换为字节[](数组) - c#

我试图将流(System.Net.ConnectStream)转换为字节数组。关于如何做到这一点的任何想法/例子? 参考方案 Stream sourceStream = ... // the ConnectStream byte[] array; using (var ms = new MemoryStream()) { sourceStream.CopyT…