为什么 SignalR 在我的 Angular Web 应用中的协商呼叫上收到 404?



我正在尝试在我的 Angular 6 应用程序中初始化 SignalR,并调用集线器的单独 ASP.Net webapi。

CORS 设置正确并允许呼叫通过,但是,我现在陷入此错误:

Debug: Sending negotiation request: http://devapi.mywebapi.com/srtest/negotiate
http://devapi.mywebapi.com/srtest/negotiate 404 (Not Found)

我已经安装了 @aspnet/信号打字稿 NPM 库的 1.0,我正在像这样初始化它:

import { Component, OnInit } from "@angular/core";
import { HubConnection, HubConnectionBuilder, LogLevel } from '@aspnet/signalr';
@Component({
selector: "test",
templateUrl: "test.component.html"
})
export class TestComponent implements OnInit {
private hubConnection: HubConnection;
constructor() { }
ngOnInit() {
this.hubConnection = new HubConnectionBuilder()
.withUrl("http://devapi.mywebapi.com/srtest")
.configureLogging(LogLevel.Debug)
.build();
this.hubConnection
.start()
.then(() => console.log('Connection started!'))
.catch(err => console.log('Error while establishing connection :('));
}
}

我的启动类定义为:

using Owin;
using Microsoft.Owin;
[assembly: OwinStartup(typeof(Api.Controllers.SignalR.Startup))]
namespace Api.Controllers.SignalR
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// Any connection or hub wire up and configuration should go here
app.MapSignalR();
}
}
}

和我的集线器类:

using Microsoft.AspNet.SignalR;
using System.Threading.Tasks;
using System.Web.Http;
namespace Api.Controllers.SignalR
{
public class SRTestHub : Hub
{
public void SendTest(string message)
{
var context = GlobalHost.ConnectionManager.GetHubContext<SRTestHub>();
context.Clients.All.receiveMessage(message);
}
}
}

我做错了什么?

存在一些问题:

1.在中心内,您都准备好了客户端属性

从中心类继承"客户端"属性。 以下就足够了:

public class SRTestHub : Hub
{
public void SendTest(string message)
{
Clients.All.receiveMessage(message);
}
}

2. 连接网址不匹配

同样在服务器部分中,您应该配置与 url 匹配的内容。服务器应该如何知道集线器在"http://devapi.mywebapi.com/srtest"上运行?

3.看起来您正在混合信号R核心和"旧"信号器。

客户端和服务器必须具有相同的版本。

我建议你阅读 https://learn.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client

如果您使用的是信号器内核,请阅读:https://learn.microsoft.com/en-us/aspnet/core/signalr/javascript-client?view=aspnetcore-2.1

最新更新