我试图获得一个非常基本的SignalR示例,它基于Microsoft's tutorial和由Visual Studio创建的WeatherForecast.NET/ANGLE SPA作为基础,因为这是我以后想要使用SignalR的同一类型的项目.The entire source code is at GitHub.

It looks as if the handshake/negotiation works and a websocket connection is established - but no messages are flowing there. This is what the Chrome Developer Tools show: enter image description here

我感觉我忽略了一些小问题,但我正在努力想知道它可能是什么.

我从调整Program.cs文件开始,这是相关代码:

builder.Services.AddSignalR(options =>
{
    options.EnableDetailedErrors = true;
});

var app = builder.Build();

...

app.UseCors();
  
//app.MapHub<ProgressHub>("/progressHub");
app.UseEndpoints(endpoints =>
{
    endpoints.MapHub<ProgressHub>("/progresshub"); // Map the hub URL here
});

app.Run();

请注意,MS建议使用app.MapHub<ProgressHub>("/progressHub");,但SOM资源建议使用app.UseEndpoints.这似乎没有什么不同.此外,我try 使用app.UseWebSockets();,但这也没有改变任何事情.此外,我还确保启用了CORS.

这是我添加的控制器方法,它应该在SignalR通道上发送消息:

[HttpPost("startProcess")]
public async Task<IActionResult> StartProcess()
{
    // Some logic to start the long-running process
    for (int i = 0; i < 10; i++)
    {
        await Task.Delay(1000);

        // Report progress to the client
        await _hubContext.Clients.All.SendAsync("ReceiveProgressUpdate", $"Step {i + 1} completed.");
    }

    return Ok("[]");
}

单步执行代码时,不会引发任何异常,代码运行时没有任何问题.在ANGLE客户端,我安装了SignalR包并创建了一个服务:

export class SignalRService {
  private hubConnection: HubConnection;
  private progressSubject: Subject<string> = new Subject<string>();

  constructor() {
    this.hubConnection = new HubConnectionBuilder()
      .withUrl('https://localhost:44429/progresshub')
      .build();

    this.hubConnection.on('ReceiveProgressUpdate', (progressMessage: string) => {
      this.progressSubject.next(progressMessage);
    });

    this.hubConnection.start().catch(err => console.error(err));
  }

  getProgressUpdates() {
    return this.progressSubject.asObservable();
  }
}

现在,我在我的SignalR组件中使用了该服务,但ProgressUpdates数组仍然为空:

export class SignalRComponent implements OnInit {
  progressUpdates: string[] = [];
  _httpClient: HttpClient;

  constructor(private httpClient: HttpClient, private signalRService: SignalRService) {
    this._httpClient = httpClient;
  }

  ngOnInit() {
    this.signalRService.getProgressUpdates().subscribe((progressMessage: string) => {
      this.progressUpdates.push(progressMessage);
    });
  }

  startProcess() {
    this.httpClient.post('https://localhost:44429/weatherforecast/startProcess', {}).subscribe();
  }
}

Also, I have turned on the WebSocket Protocol in Windows as this was suggested on SO as well: enter image description here

推荐答案

我下载您的回购并更改proxy.conf.js文件,如下所示.而且它运行得很好.您可以根据需要更改其他设置.

我还启用了客户端日志(log)记录,以便我们可以建立连接.

Test Result

enter image description here

proxy.conf.js

const { env } = require('process');

const target = env.ASPNETCORE_HTTPS_PORT ? `https://localhost:${env.ASPNETCORE_HTTPS_PORT}` :
  env.ASPNETCORE_URLS ? env.ASPNETCORE_URLS.split(';')[0] : 'http://localhost:50822';



const PROXY_CONFIG = [
  {
    context: [
      "/weatherforecast",
      "/progresshub"
   ],
    target: target, 
    changeOrigin: true,  
    logLevel: "debug",
    rejectUnauthorzied: true, 
    secure: false,            
    strictSSL: true,          
    withCredentials: true,
    ws: true
  }
]

module.exports = PROXY_CONFIG;

signal-r.service.ts

import { Injectable } from '@angular/core';
import { HubConnection, HubConnectionBuilder } from '@microsoft/signalr';
import * as signalR from '@microsoft/signalr';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class SignalRService {
  private hubConnection: HubConnection;
  private progressSubject: Subject<string> = new Subject<string>();

  constructor() {
    this.hubConnection = new signalR.HubConnectionBuilder()
      .withUrl('https://localhost:44429/progresshub', signalR.HttpTransportType.WebSockets | signalR.HttpTransportType.LongPolling).configureLogging(signalR.LogLevel.Debug)
      .build();

    this.hubConnection.on('ReceiveProgressUpdate', (progressMessage: string) => {
      this.progressSubject.next(progressMessage);
    });
    this.hubConnection.start().catch(err => console.error(err));
  }

  getProgressUpdates() {
    return this.progressSubject.asObservable();
  }
}

Angular相关问答推荐

他们如何删除Clarity中的Angular组件包装器元素

RFDC.CommonJS或AMD依赖项可能会导致优化救助ANGURAL PROCEMENT with ngx-charts lib

如何在Angular 17中使用Angular—calendum?

NG构建后多余的国旗

有没有其他代码可以用函数的方式写成Angular ?

Angular :为什么我得到了一个可观察到的共鸣

如何使用formBuilder.Group()从角形表单中删除选定的选项?

懒惰加载角404路径

Angular 17水化-POST请求同时触发客户端/服务器端,而GET请求仅触发服务器端?

Angular 路由中的模块构建失败

Angular Signals 如何影响 RXJS Observables 以及在这种情况下变化检测会发生什么

在 Angular 14 中找不到命名空间google

RxJS 基于先前的数据响应执行请求(涉及循环对象数组)

Subject.complete() 是否取消订阅所有听众?

ng test 和 ng e2e 之间的真正区别是什么

Angular2 测试 - 按 ID 获取元素

如何将服务变量传递到 Angular Material 对话框?

Angularmaterial步进器:禁用标题导航

实现自定义 NgbDateParserFormatter 来更改 NgbInputDatepicker 上输入值的格式是否正确?

Angular2动态改变CSS属性