![](/img/trans.png)
[英]SignalR callback seems not firing in ASP.NET Core 6 Web API with .NET 6 Winforms client
[英]Add SignalR to Net6 Web Api and connect from Winforms application (.net fx4.8) - hub not found
我正在嘗試將 signalr 添加到 webapi,我創建了 CucinaHub class:
public class CucinaHub : Hub
{
static ConcurrentDictionary<string, string> _users = new ConcurrentDictionary<string, string>();
#region Client Methods
public void SetUserName(string userName)
{
_users[Context.ConnectionId] = userName;
}
#endregion Client Methods
}
並配置 SignalR:
services.AddSignalR();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<CucinaHub>("/cucinahub");
});
然后在 Windows 表單應用程序中,我使用此代碼連接集線器:
_signalRConnection = new HubConnection($"{Properties.Settings.Default.URL}/api", true);
_hubProxy = _signalRConnection.CreateHubProxy("/cucinahub");
_hubProxy.On("GetValvole", async () => await GetValvole());
try
{
//Connect to the server
await _signalRConnection.Start();
}
catch (Exception ex)
{
Log.Error(ex.ToString());
}
我總是得到 404 響應代碼:
宿主環境:開發內容根路徑:D:\SwDev\PigsutffHTML\Server\Common\Common.WebApiCore 現在監聽:http://localhost:5000 應用啟動。 按 Ctrl+C 關閉。 信息:Microsoft.AspNetCore.Hosting.Diagnostics[1] 請求開始 HTTP/1.1 GET http://localhost:5000/api/signalr/negotiate?clientProtocol=2.1&connectionData=[%7B%22Name%22:%22/cucinahub% 22%7D] - - 警告:Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware[3] 無法確定用於重定向的 https 端口。 信息:Microsoft.AspNetCore.Hosting.Diagnostics[2] 請求完成 HTTP/1.1 GET http://localhost:5000/api/signalr/negotiate?clientProtocol=2.1&connectionData=[%7B%22Name%22:%22/cucinahub% 22%7D] - - - 404 0 - 122.4090 毫秒
錯誤在哪里? 謝謝
簡短回答 - 您不能混合使用 .NET 4.x 框架和 .NET 核心服務器/客戶端。 雙方都無法與對方交談。 你必須升級你的客戶端。 此 SO 答案中的更多信息。
關鍵是在 WinForm 項目上使用 package Microsoft.AspNetCore.SignalR.Client
作為客戶端。 它在 .NETFramework 上可用。 你可以從這里的圖片中看到:
出於測試目的,我創建了一個 webapi 項目和另一個 winform 項目。 Winform工程已經安裝好package,接下來就可以按照MS文檔在webapi工程中設置hubs了。
然后先啟動webapi項目,看看它運行在哪個端口上。 現在您可以按照MS Document for setting Clients來設置客戶端連接到集線器。 出於測試目的,我創建了兩個按鈕功能來連接集線器並向集線器發送消息,這里是連接和發送消息 function 按鈕的代碼:
private void btnconnect_Click(object sender, EventArgs e)
{
try
{
connection.StartAsync().Wait();
}
catch (Exception ex)
{
//...
}
}
private void btnsend_Click(object sender, EventArgs e)
{
try
{
connection.InvokeAsync("SendMessage",
"winformclient", "hello world").Wait();
}
catch (Exception ex)
{
//...
}
}
這是設置客戶端連接的代碼(記住在這里使用你自己的端口):
HubConnection connection;
public Form1()
{
InitializeComponent();
connection = new HubConnectionBuilder()
.WithUrl("https://localhost:7090/ChatHub")
.Build();
connection.Closed += async (error) =>
{
await Task.Delay(new Random().Next(0, 5) * 1000);
await connection.StartAsync();
};
}
現在啟動WinForm應用程序,點擊發送按鈕,你可以在這里得到結果:
您可以從屏幕截圖中看到,集線器已經從 WinForm 應用程序中獲取消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.