简体   繁体   English

将 SignalR 添加到 Net6 Web Api 并从 Winforms 应用程序 (.net fx4.8) 连接 - 未找到集线器

[英]Add SignalR to Net6 Web Api and connect from Winforms application (.net fx4.8) - hub not found

I'm trying to add signalr to the webapi, I create the CucinaHub class:我正在尝试将 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
}

and configure SignalR:并配置 SignalR:

services.AddSignalR();

app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapHub<CucinaHub>("/cucinahub");
        });

Then in Windows form application I use this code to connect with the hub:然后在 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());
        }

I get always 404 response code:我总是得到 404 响应代码:

Hosting environment: Development Content root path: D:\SwDev\PigsutffHTML\Server\Common\Common.WebApiCore Now listening on: http://localhost:5000 Application started.宿主环境:开发内容根路径:D:\SwDev\PigsutffHTML\Server\Common\Common.WebApiCore 现在监听:http://localhost:5000 应用启动。 Press Ctrl+C to shut down.按 Ctrl+C 关闭。 info: Microsoft.AspNetCore.Hosting.Diagnostics[1] Request starting HTTP/1.1 GET http://localhost:5000/api/signalr/negotiate?clientProtocol=2.1&connectionData=[%7B%22Name%22:%22/cucinahub%22%7D] - - warn: Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware[3] Failed to determine the https port for redirect.信息: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 端口。 info: Microsoft.AspNetCore.Hosting.Diagnostics[2] Request finished HTTP/1.1 GET http://localhost:5000/api/signalr/negotiate?clientProtocol=2.1&connectionData=[%7B%22Name%22:%22/cucinahub%22%7D] - - - 404 0 - 122.4090ms信息: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 毫秒

Where is the error?错误在哪里? Thank you谢谢

Short answer - You cannot mix the .NET 4.x Framework and the .NET Core server/clients.简短回答 - 您不能混合使用 .NET 4.x 框架和 .NET 核心服务器/客户端。 Neither one can talk to the other.双方都无法与对方交谈。 You have to upgrade your client.你必须升级你的客户端。 More info in this SO answer .此 SO 答案中的更多信息。

The key is using the package Microsoft.AspNetCore.SignalR.Client on the WinForm project as client.关键是在 WinForm 项目上使用 package Microsoft.AspNetCore.SignalR.Client作为客户端。 It is available on .NETFramework.它在 .NETFramework 上可用。 You can see from the picture here:你可以从这里的图片中看到: 在此处输入图像描述

For testing purpose, I created one webapi project and another winform project.出于测试目的,我创建了一个 webapi 项目和另一个 winform 项目。 Winform project has been installed the package. Then you can follow the MS document to set up the hubs in webapi project. Winform工程已经安装好package,接下来就可以按照MS文档在webapi工程中设置hubs了。

Then start the webapi project first to see which port it's running on.然后先启动webapi项目,看看它运行在哪个端口上。 Now you can follow the MS Document for setting Clients to set client connect to hub.现在您可以按照MS Document for setting Clients来设置客户端连接到集线器。 For testing purpose, I created two button functions to connect hub and send message to hub, here is the code of connect and send message function button:出于测试目的,我创建了两个按钮功能来连接集线器并向集线器发送消息,这里是连接和发送消息 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)
        {
            //...
        }
    }

And here is the code for setting up client connecting( Remember using your own port here ):这是设置客户端连接的代码(记住在这里使用你自己的端口):

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();
        };
    }

Now start the WinForm Application, click the send button and you can get the result here:现在启动WinForm应用程序,点击发送按钮,你可以在这里得到结果: 在此处输入图像描述

You can see from the screenshot, the hub has already got the message from WinForm application.您可以从屏幕截图中看到,集线器已经从 WinForm 应用程序中获取消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 SignalR 回调似乎没有在 ASP.NET Core 6 Web API 和 .NET 6 Winforms 客户端中触发 - SignalR callback seems not firing in ASP.NET Core 6 Web API with .NET 6 Winforms client 在 Winforms in.Net6 中通过 url 显示 Html 页面 - Display Html page via url in Winforms in .Net6 .net和winforms的.Net身份验证 - .Net authentication for both web and winforms ADAL.NET Winforms应用程序 - ADAL.NET winforms application 是否可以从Winforms应用程序托管asp.net mvc网站? - Is it possible to host a asp.net mvc website from a winforms application? 从.Net WinForms应用程序以编程方式刷新浏览器的页面 - Refresh browser's page programmatically, from a .Net WinForms application 从 .net 2.0 WinForms 应用程序以编程方式设置 DPI - Programmatically set the DPI from a .net 2.0 WinForms application 从asp.net core web api下载大文件到winforms抛出json长度值过大不支持 - Downloading large file from asp.net core web api to winforms throws json value of length is large and not supported 使用ASP.net凭据从WinForms应用程序登录 - Using ASP.net credentials to log in from a WinForms application 以图形方式模拟.NET winforms应用程序 - Graphically template a .NET winforms application
 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM