我在带有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());
});
}
HUB类
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;
}
}
}
}
我想将SingalR消息从Web api推送到WPF,我的意思是我希望消息在Web页面上显示的同时出现在WPF中。现在,SignalR消息仅显示在网站上。它没有显示在WPF应用程序中。如果您有任何想法请咨询。
谢谢
答案 0 :(得分:0)
我根据用户@ mm8的评论发布了此答案。
我在WPF应用程序部分进行了一些更改。首先,我从nuget中添加了Microsoft.AspNetCore.SignalR.Client
。然后如下所示更改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;
}
}
现在可以正常工作了。非常感谢你@ mm8