当我的解决方案中有两个项目时,如何为SignalR 3.0指定正确的后端URL?当前正在获取404

问题描述 投票:0回答:2

在我的SignalR项目中遇到此错误:

Failed to load resource: the server responded with a status of 404,

...我调用connection.start()后解雇了一段时间>

[C0成功之后,我修改了它在单个解决方案中使用两个项目,即后端和前端。

  • 后端是.NET Core Web API项目
  • 前端是.NET Core Web应用程序
  • 在后端startup.cs文件中,我尝试使用'ChatHub'指定URL,如下所示:

this tutorial

我将以上代码放在我的后端项目的Startup.cs文件中。根据教程,还以app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapHub<ChatHub>("/chatHub"); }); 方法在同一文件中添加了services.AddSignalR();

我从教程中剪切并粘贴了我的Hub代码。

除了上面的错误消息,调试器还指示:

  • ConfigureServices
  • Information: Normalizing '/chatHub' to 'https://localhost:44365/chatHub'
  • 我从字面上剪切并粘贴了我的前端的JavaScript,请注意下面第2行显示的URL,该URL应该与上面的端点匹配:

Error: Failed to complete negotiation with the server

此代码将引发上面列出的错误。我在URL上尝试了一些变体,包括"use strict"; var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build(); //Disable send button until connection is established document.getElementById("sendButton").disabled = true; connection.on("ReceiveMessage", function (user, message) { var msg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); var encodedMsg = user + " says " + msg; var li = document.createElement("li"); li.textContent = encodedMsg; document.getElementById("messagesList").appendChild(li); }); connection.start().then(function () { document.getElementById("sendButton").disabled = false; }).catch(function (err) { return console.error(err.toString()); }); document.getElementById("sendButton").addEventListener("click", function (event) { var user = document.getElementById("userInput").value; var message = document.getElementById("messageInput").value; connection.invoke("SendMessage", user, message).catch(function (err) { return console.error(err.toString()); }); event.preventDefault(); }); 。没运气。

然后,我尝试拆分解决方案并分别运行每个项目。修改了我的JavaScript以使用后端端口,如下所示:

https://localhost:44365/BackEnd/ChatHub

但是当我检查浏览器时,它指示了

var connection = new signalR.HubConnectionBuilder()
    .withUrl("https://localhost:44384/chatHub")
    .build();

请注意,它使用的端口是错误的端口,它是前端的端口。

摘要

我相信我学习了一个有效的教程,并仅通过将其分为两个项目对其进行了修改,但是我无法弄清楚该URL以连接到我的后端。我尝试对URL进行变体,由于某些原因,当我从原始解决方案中分离出后端项目时,它没有使用正确的端口。

Information: Normalizing '/chatHub' to 'https://localhost:*44365*/chatHub'.

在我的SignalR项目中遇到此错误:无法加载资源:服务器响应状态为404,...调用connection.start()后触发了一段时间。此操作成功后...

c# asp.net-core signalr
2个回答
1
投票
在学习完本教程之后,我修改了它在单个解决方案中使用两个项目的后端和前端。

0
投票
我通过遵循Fei Han的建议并添加enter image description here使其得以正常运行。另外,您必须按正确的顺序调用UseCors,否则会遇到令人沮丧的错误。这是后端中Startup.cs的相关代码:
© www.soinside.com 2019 - 2024. All rights reserved.