C# 如果连接未处于连接状态,.NET core angular project无法发送数据?

C# 如果连接未处于连接状态,.NET core angular project无法发送数据?,c#,angular,asp.net-core,.net-core,signalr,C#,Angular,Asp.net Core,.net Core,Signalr,我正在windows上的VScode中运行一个.NET core angular项目,我正在尝试让signalR工作,但不幸的是事情似乎并没有按照我的方式进行。以前,当我用相同的代码将angular和.NET core项目分开(web API和angular项目分开)时,这个问题没有发生。当我切换到一个.NET core angular项目时,它正在发生。提前谢谢 当我尝试向服务器发送消息时,出现以下错误 ChatHub.cs using System; using System.Thread

我正在windows上的VScode中运行一个.NET core angular项目,我正在尝试让signalR工作,但不幸的是事情似乎并没有按照我的方式进行。以前,当我用相同的代码将angular和.NET core项目分开(web API和angular项目分开)时,这个问题没有发生。当我切换到一个.NET core angular项目时,它正在发生。提前谢谢

当我尝试向服务器发送消息时,出现以下错误

ChatHub.cs

using System;
using System.Threading.Tasks;
using System.Collections.Generic;

using Microsoft.AspNetCore.SignalR;

namespace ProjectConker
{
    public class IMessage
    {
       public string timestamp;
       public string message;
       public string author;
       public string iconLink;
   }
    public class ChatHub : Hub
    {
        public Task SendToAll(string name, IMessage messageData)
        {
            Console.WriteLine(messageData.message);
             return Clients.All.SendAsync("ReceiveMessage", name, messageData);
        }
    } 
}
角度客户端组件


import { Component, OnInit } from '@angular/core';
import { ITag } from '../Tag/tag';
import { TagComponent } from '../Tag/tag.component';
import { Router, ActivatedRoute, ParamMap, Params } from '@angular/router';
import { switchMap } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { IMessage } from './Message';
import { HubConnection, HubConnectionBuilder, HttpTransportType } from '@aspnet/signalr';
import { HttpClient } from '@angular/common/http';



@Component({
  selector: 'chat',
  templateUrl: "./chatComponent.component.html",
  styleUrls: ['./chatComponent.component.css']
  // providers: [ ChatService ]
})

export class ChatComponent implements OnInit {

  hubConnection: HubConnection;

  messageData: IMessage;
  message: string;

  //profile info
  author: string;
  iconLink: string;

  messages: IMessage[] = [];

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private http: HttpClient
  ) { }

  ngOnInit() {

    this.getRandomUser();

    this.hubConnection = new HubConnectionBuilder().withUrl("http://localhost:5000/api/chat", {
      skipNegotiation: true,
      transport: HttpTransportType.WebSockets
    }).build();

    this.hubConnection
      .start()
      .then(() => console.log('Connection started!'))
      .catch(err => console.log('Error while establishing connection :('));

    this.hubConnection.on('ReceiveMessage', (author: string, receivedMessage: IMessage) => {

      this.messages.push(receivedMessage);
    });

  }

  private getRandomUser() {
    this.http.get("https://randomuser.me/api/")
      .subscribe(
        (data: any) => {
          console.log(data);

          this.iconLink = data.results[0].picture.medium;
          this.author = data.results[0].name.first;

          console.log(this.iconLink);
        }
      );

  }

  public sendMessage(): void {

    var today = new Date();

    this.messageData = {
      author: this.author,
      message: this.message,
      timestamp: ("0" + today.getHours()).toString().slice(-2) + ":" + ("0" + today.getMinutes()).toString().slice(-2),
      iconLink: this.iconLink
    };
    this.hubConnection
      .invoke('SendToAll', this.author, this.messageData)
      .catch(err => console.error(err));

    this.message = '';
  }


}
角度客户端视图

 <div class="outer-chat-container">
    <div class="chat-container">

        <ng-container *ngIf="messages.length > 0">
            <div class="message-box"  *ngFor="let message of messages">
              <img class="avatar" [src]='message.iconLink'>


              <div class="content">
                <div class="headline">
                    <p class="author">{{ message.author }}</p>
                    <div class="datetime">{{ message.timestamp }}</div>
                </div>


                <p class="message">{{ message.message }}</p>
              </div>
            </div>

         </ng-container>
    </div>
    <form class="send-message-form" (ngSubmit)="sendMessage()" #chatForm="ngForm">
        <div>
            <input type="text" name="message" [(ngModel)]="message" placeholder="Your message" required>
            <button type="submit">Send</button>
        </div>
    </form>
</div>

让我们回顾一下您的
ChatComponent
组件,它初始化并尝试建立到集线器的连接。它的
ngOnInit()
在为
ReceiveMessage
绑定事件处理程序后立即返回

ngOnInit(){
...
this.hubConnection=new-HubConnectionBuilder().withUrl(…).build();
这是hubConnection
.start()
。然后(()=>console.log('连接已启动!'))
.catch(err=>console.log('建立连接时出错:(');
this.hubConnection.on('ReceiveMessage',…);
}
注意:连接到集线器将需要一些时间。如果在建立连接之前尝试向服务器发送消息,则会抛出

如何修复: 创建一个
表格
,以确保已建立连接

private thenable: Promise<void> ngOnInit() { ... this.hubConnection = new HubConnectionBuilder().withUrl(...).build(); this.start() this.hubConnection.on('ReceiveMessage', ...); } private start() { this.thenable = this.hubConnection.start(); this.thenable .then(() => console.log('Connection started!')) .catch(err => console.log('Error while establishing connection :(')); }
[更新]

您的代码中还有两个错误:

  • 您在Spa中间件之后注册了SignalR中间件。请注意,
    UseSpa()
    应被用作一个包罗万象的中间件。您应在
    UseSpa()之前调用
    usesigner()

    app.usesigner(路由=> { routes.MapHub(“/api/chat”); }); app.UseMvc(路由=> { ... }); app.UseSpa(spa=> { ... }); app.usesigner(路由=> { routes.MapHub(“/api/chat”); });
  • 如果连接到同一服务器,请避免使用硬编码url:

    this.hubConnection = new HubConnectionBuilder().withUrl("http://localhost:5000/api/chat", { skipNegotiation: true, transport: HttpTransportType.WebSockets }).build(); this.hubConnection=新的HubConnectionBuilder()。带有URL(“http://localhost:5000/api/chat", { skipNegotiation:没错, 传输:HttpTransportType.WebSockets }).build(); 否则,当您使用不同的端口/协议时,它将失败


  • 调用
    sendmessage
    的位置/时间?当我这样做时,sendmessage中的this.thenable.then()不会运行,也不会出现错误。@WasiimOuro这没有意义。你怎么知道
    this.thenable.then()呢
    在sendMessage中未运行?@WasiimOuro您在控制台中是否发现任何消息,表明连接已启动!
    或建立连接时出现
    错误:(
    ?我发现两者都没有,只是为空。虽然sendMessage确实被调用。@WasiimOuro能否请您放置
    控制台.log(
    已执行)
    中,然后((0=>{…})
    查看输出?我这样问是因为如果不执行它就没有意义了。
    C:\Users\wasii\Documents\CodingProjects\ProjectConker>dotnet --info
    .NET Core SDK (reflecting any global.json):
     Version:   2.2.402
     Commit:    c7f2f96116
    
    Runtime Environment:
     OS Name:     Windows
     OS Version:  10.0.18362
     OS Platform: Windows
     RID:         win10-x64
     Base Path:   C:\Program Files\dotnet\sdk\2.2.402\
    
    Host (useful for support):
      Version: 2.2.7
      Commit:  b1e29ae826
    
    .NET Core SDKs installed:
      2.2.402 [C:\Program Files\dotnet\sdk]
    
    .NET Core runtimes installed:
      Microsoft.AspNetCore.All 2.2.7 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All]
      Microsoft.AspNetCore.App 2.2.7 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
      Microsoft.NETCore.App 2.2.7 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
    
    To install additional .NET Core runtimes or SDKs:
      https://aka.ms/dotnet-download
    
    
    private thenable: Promise<void> ngOnInit() { ... this.hubConnection = new HubConnectionBuilder().withUrl(...).build(); this.start() this.hubConnection.on('ReceiveMessage', ...); } private start() { this.thenable = this.hubConnection.start(); this.thenable .then(() => console.log('Connection started!')) .catch(err => console.log('Error while establishing connection :(')); } public sendMessage(): void { this.thenable.then(() =>{ var today = new Date(); this.messageData = ... this.hubConnection .invoke('SendToAll', this.author, this.messageData) .catch(err => console.error(err)); this.message = ''; }); } app.UseSignalR(routes => { routes.MapHub<ChatHub>("/api/chat"); }); app.UseMvc(routes => { ... }); app.UseSpa(spa => { ... }); app.UseSignalR(routes => { routes.MapHub<ChatHub>("/api/chat"); }); this.hubConnection = new HubConnectionBuilder().withUrl("http://localhost:5000/api/chat", { skipNegotiation: true, transport: HttpTransportType.WebSockets }).build();