我正在try 使用.Net Core Web API(服务器端)和控制台应用程序(客户端)来实现SignalR,以了解其工作原理.

下面是我的starp.cs代码:

public void ConfigureServices(IServiceCollection services)
{

    services.AddControllers();
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "SignalR", Version = "v1" });
    });
    //Service for SignalR
    services.AddSignalR();
    services.AddCors(c =>
    {
        c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
    });
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseSwagger();
        app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "SignalR v1"));
    }

    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseAuthorization();

    app.UseCors(o=>o.AllowAnyOrigin());

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        //Endpoint map for ChatHub, which I've created
        endpoints.MapHub<ChatHub>("/chathub");
    });
}  

以下是我的ChatHub类:

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

以下是我的控制台应用程序(创建为SignalR客户端):

static async Task Main(string[] args)
       {
           try
           {
               HubConnection connection = new HubConnectionBuilder().WithUrl("https://localhost:44340/chathub").WithAutomaticReconnect().Build();

               await connection.StartAsync();

               if(connection.State == HubConnectionState.Connected)
               {
                   Console.WriteLine("Connected ... Please type message now");
                   var message = "Hey";
                   //Getting hit to SendMessage method defined in  ChatHub Class
                   await connection.InvokeAsync("SendMessage", message);
                   Console.WriteLine(connection.ConnectionId);
                   /*
                    Connection.On is not working and unable to writeline on console.
                    I am expecting result Hey on Console.
                    */
                   connection.On<string>("ReceiveMessage", m =>
                   {
                       Console.WriteLine(m);
                   });
               }
           }
           catch (Exception ex)
           {

               Console.WriteLine(ex.Message);
           }
       }

I am expecting Result : ConnectionId
Hey
But I am getting: ConnectionId

推荐答案

由于您的connection.On注册事件太晚,SignalR在.Net Core Web API上广播完成.所以你不能得到这条信息.

您可以将connection.On注册事件移到connection.InvokeAsync方法之前,然后您可以看到‘嘿’消息.

// ...
// Register event
connection.On<string>("ReceiveMessage", m =>
{
   Console.WriteLine(m);
});

if(connection.State == HubConnectionState.Connected)
{
   Console.WriteLine("Connected ... Please type message now");
   var message = "Hey";    
   await connection.InvokeAsync("SendMessage", message);
   Console.WriteLine(connection.ConnectionId);    
}

// Result:
// Connected ... Please type message now
// Hey
// ConnectionId

如果您想要在Hey条消息之前发送ConnectionId条消息,您可以更改此选项.

// ...
// Register event
connection.On<string>("ReceiveMessage", m =>
{
   Console.WriteLine(m);
});

if(connection.State == HubConnectionState.Connected)
{
   Console.WriteLine("Connected ... Please type message now");
   var message = "Hey";

   // call async method and wait later
   var task = connection.InvokeAsync("SendMessage", message);
   Console.WriteLine(connection.ConnectionId);    

   // wait SendMessage
   await task;
}

// Result:
// Connected ... Please type message now
// ConnectionId
// Hey

Csharp相关问答推荐

PostingAsJsonAschange在从调用的方法返回时给出500错误

VS Code - C# - dotnet run找不到文件,但我可以打开并编辑它们吗?

ß != ss与ICU进行不区分大小写的比较

C#中的包版本控制

EF Core:看不到任何查询日志(log)?

C# uwp中的Win11启动屏幕剪辑工作方式不同

如何在NServicebus中配置学习传输的文件夹(NService bus 8)

Entity Framework Core 8 dbcontext—无法以多对多关系添加某些行'

如何在Visual Studio代码中更改大括号模式{},用于C#语言

在发布表单时绑定包含附加(嵌套)列表的对象列表的正确语法是什么

将XPS转换为PDF C#

如何在Windows 11任务调度程序中每1分钟重复一次任务?

在C#中,非静态接口方法的抽象和虚拟是冗余的吗?

ASP.NET Core MVC将值从视图传递到控制器时出现问题

RabbitMQ群集的MassTransit配置问题

具有类型识别的泛型方法

基于C#方法的EF核心过滤查询(缓冲与流)

在同一个捕获中可以有多种类型的异常吗?

try 访问字典中的模拟对象时引发KeyNotFoundException

为什么连接到Google OAuth2后,结果.Credential为空?