问题详情
59 | 清风大侠
SignalR通知及控制台日志示例
  1. 在后台业务服务类中使用INotifyService发送通知
[WebApi, Service] // 构造函数注入INotifyService
class HomeService(Context context, INotifyService service) : ServiceBase(context)
{
    public Task DoXXXXAsync()
    {
        // 往母版页发送系统通知
        service.LayoutNotifyAsync("系统通知", "XXX服务已启动!");
    }
}
  1. KConsole组件使用示例
  • 在后端添加TestWorker后台服务
public class AppConstant
{
    public const string AddLog = "AddLog"; // 定义SignalR方法名
}

class TestWorker(INotifyService service) : BackgroundService
{
    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        return Task.Run(() =>
        {
            while (true)
            {
                // 每秒往BizId为Test的控制台组件发送日志
                service.SendAsync(AppConstant.AddLog, new ConsoleLogInfo
                {
                    BizId = "Test",
                    Type = ConsoleLogType.Info,
                    Content = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} 测试日志信息"
                }, stoppingToken);
                Thread.Sleep(1000);
            }
        });
    }
}
  • 在后端AppServer中注册TestWorker
static class AppServer
{
    internal static void AddApplicationWeb(this IServiceCollection services, Action<CoreOption> action)
    {
        services.AddHostedService<TestWorker>(); // 注册TestWorker
    }
}
  • 在前端添加组件显示实时日志
<KButton Type="@ButtonType.Primary" Name="日志" OnClick="OnLog" />
@code {
    // 弹窗显示控制台日志组件,实时显示TestWorker发送的日志
    private void OnLog()
    {
        var model = new DialogModel
        {
            Title = "控制台日志",
            Width = 600,
            Content = b => b.Div("kui-p10", () =>
            {
                // BizId:日志业务ID
                // MethodName:SignalR方法名
                b.Component<KConsole>().Set(c => c.BizId, "Test").Set(c => c.MethodName, AppConstant.AddLog).Build();
            })
        };
        UI.ShowDialog(model);
    }
}
回复列表

暂无数据

上午好!