要实现在ASP.NET Core 3.1中使用Worker Service模板和SignalR,您可以按照以下步骤进行操作:
创建一个新的ASP.NET Core Worker Service项目。您可以使用Visual Studio或者通过命令行运行dotnet new worker -n MyWorkerService
来创建项目。
安装必需的NuGet包。在项目的.csproj文件中,添加以下NuGet包引用:
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace MyWorkerService
{
public class Worker : BackgroundService
{
private readonly ILogger _logger;
private HubConnection _hubConnection;
public Worker(ILogger logger)
{
_logger = logger;
}
public override async Task StartAsync(CancellationToken cancellationToken)
{
_hubConnection = new HubConnectionBuilder()
.WithUrl("https://localhost:5001/chatHub") // Replace with your SignalR Hub URL
.Build();
_hubConnection.Closed += async (exception) =>
{
await Task.Delay(new Random().Next(0, 5) * 1000);
await _hubConnection.StartAsync();
};
await _hubConnection.StartAsync();
await base.StartAsync(cancellationToken);
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
await _hubConnection.StopAsync();
await base.StopAsync(cancellationToken);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
// Call SignalR hub method
await _hubConnection.SendAsync("SendMessage", "Worker Service", "Hello from Worker Service!");
await Task.Delay(10000, stoppingToken);
}
}
}
}
ChatHub.cs
的新类文件,并添加以下代码:using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
namespace MyWorkerService
{
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
}
CreateHostBuilder
方法中的代码替换为以下内容:public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup();
});
Startup.cs
的新类文件,并添加以下代码:using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace MyWorkerService
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub("/chatHub"); // Replace with your desired SignalR Hub URL
});
}
}
}
dotnet run
命令来运行项目。现在,您的ASP.NET Core Worker Service应该能够与SignalR Hub进行通信,并发送消息到SignalR客户端。