首页 > 解决方案 > 无法在 SignalR 与 WPF 客户端之间建立连接

问题描述

我在带有 SignalR(JavaScript 客户端)的 ASP.NET Core 中有一个 WEB API 应用程序。这是我的启动配置:

    public IServiceProvider ConfigureServices(IServiceCollection services)
    {

        ....................................

        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                policy => policy.WithOrigins(Configuration.GetSection("ApplicationPortalURL").Value)
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());
        });

        ............................................


        services.AddSingleton<MyHub>();

        services.AddSignalR();

        ............................................

        services.AddMvc();
        .AddControllersAsServices()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        var builder = new ContainerBuilder();

        builder.Populate(services);
        ApplicationContainer = builder.Build();
        return new AutofacServiceProvider(ApplicationContainer);
    }


    public async void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseCors("CorsPolicy");


        app.UseSignalR(routes =>
        {
            routes.MapHub<MyHub>("/MyHub");
        });


        app.UseMvc();

        var bus = ApplicationContainer.Resolve<IBusControl>();
        await Task.Run(() =>
        {
            var busHandle = TaskUtil.Await(() => bus.StartAsync());
            lifetime.ApplicationStopping.Register(() => busHandle.Stop());
        });
    }

集线器类

 public class MyHub : Hub
{

    public static HashSet<string> CurrentConnections = new HashSet<string>();

    public async override Task OnConnectedAsync()
    {
        await base.OnConnectedAsync();
    }

    public async override Task OnDisconnectedAsync(Exception exception)
    {
        await base.OnDisconnectedAsync(exception);
    }

    public async Task SendMessage(string message)
    {
        await Clients.All.SendAsync("sendmessage", message);
    }
}

Javascript

const connection = new signalR.HubConnectionBuilder()
    .withUrl("http://localhost:33300/MyHub", {
        skipNegotiation: true,
        transport: signalR.HttpTransportType.WebSockets
    }).build();

connection.on("sendmessage", (message) => {
    debugger;
    altert(message);
});

connection.start().then(function (client) {
    console.log('Signal r connection started.');
    console.log(client);
}).catch(function (err) {
    return console.error(err);
});

网站部分一切正常。但我也有一个 WPF 客户端。

WPF 客户端

namespace WpfAppSignalRClient
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        InitializeSignalR();
    }
    private void InitializeSignalR()
    {
        try
        {
            var hubConnection = new HubConnection("http://localhost:33300/");
            var prestoHubProxy = hubConnection.CreateHubProxy("MyHub");
            prestoHubProxy.On<string>("sendmessage", (message) =>
            {
                MessageBox.Show(message);
            });
            hubConnection.Start();
        }
        catch (System.Exception ex)
        {

            throw ex;
        }
    }
}
}

我想将 SignalR 消息从 web api 推送到 WPF。我的意思是我希望消息出现在 WPF 中的同时消息显示在网页中。现在 SignalR 消息只显示在网站中,它没有显示在 WPF 应用程序中。

标签: c#.netwpfasp.net-coresignalr

解决方案


我根据用户@mm8 的评论发布了这个答案。

我在我的 WPF 应用程序部分做了一些更改。首先我Microsoft.AspNetCore.SignalR.Client从nuget添加。然后更改 SignalR 连接代码,如下所示。

  private async void InitializeSignalR()
    {
        try
        {
            connection = new HubConnectionBuilder()
                        .WithUrl("http://localhost:33300/MyHub")
                        .Build();

            #region snippet_ClosedRestart
            connection.Closed += async (error) =>
            {
                await Task.Delay(new Random().Next(0, 5) * 1000);
                await connection.StartAsync();
            };
            #endregion

            #region snippet_ConnectionOn
           connection.On<string>("sendmessage", (message) =>
           {
               this.Dispatcher.Invoke(() =>
               {
                   lstListBox.Items.Add(message);
               });
           });

            #endregion

            try
            {
                await connection.StartAsync();
                lstListBox.Items.Add("Connection started");
                //connectButton.IsEnabled = false;
                btnSend.IsEnabled = true;
            }
            catch (Exception ex)
            {
                lstListBox.Items.Add(ex.Message);
            }
        }
        catch (System.Exception ex)
        {

            throw ex;
        }
    }

现在它工作正常。


推荐阅读