首页 > 解决方案 > SignalR .Net Core 3.1 Web 应用程序无法在本地 IIS 上运行

问题描述

尝试基于使用 ASP.Net Core 3.1 和 Angular 的在线示例创建聊天。

以下在 IIS Express 上运行良好,但在本地 IIS 上运行良好。

错误消息:WebSocketTransport.js:85 WebSocket 连接到“ws://localhost/MyCoreAPI/ChatHub”失败:WebSocket 握手期间出错:意外响应代码:400

启动:

    public void ConfigureServices(IServiceCollection services)
    { 
        services.AddSignalR();
    }
    public void Configure(IApplicationBuilder app, 
                          IWebHostEnvironment env, 
                          ApplicationDbContext context)
    {

        app.UseCors("EnableCORS");
        app.UseMiddleware<ErrorHandlingMiddleware>();
        app.UseMiddleware<TokenServiceMiddleware>();

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(route =>
        {
            route.MapHub<ChatHub>("/ChatHub");
        });
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=auth}/{action}/");

        });


        app.Run(async (c) =>
        {
            await c.Response.WriteAsync("My Core Web API");
        });
    }

聊天中心:

public class ChatHub : Hub
{
    public Task SendMessageToAll(Message message) =>
         Clients.All.SendAsync("receiveMessage", message);
}

客户:

export class ChatService {

  receiveMessage = new EventEmitter<Message>();  
  connectionEstablished = new EventEmitter<Boolean>();  

  private connectionIsEstablished = false;  
  private _hubConnection: HubConnection;  

  constructor() {  
    this.createConnection();  
    this.registerOnServerEvents();  
    this.startConnection();  
  }  

  async sendMessage(message: Message) {  
    console.log(message);
    await this._hubConnection.invoke('SendMessageToAll', message);  
  }  

  private createConnection() {  
    this._hubConnection = new HubConnectionBuilder()
      .configureLogging(LogLevel.Debug)  
      .withUrl('http://localhost/MyCoreAPI/ChatHub', {
        skipNegotiation:true,
        transport:HttpTransportType.WebSockets
      })  
      .build();  
  }  

  private startConnection(): void {  
    this._hubConnection  
      .start()  
      .then(() => {  
        this.connectionIsEstablished = true;  
        console.log('Hub connection started');  
        this.connectionEstablished.emit(true);  
      })  
      .catch(err => {  
        console.log('Error while establishing connection, retrying...');  
        setTimeout(function () { this.startConnection(); }, 5000);  
      });  
  }  

  private registerOnServerEvents(): void {  
    this._hubConnection.on('receiveMessage', (data: any) => {
      console.log(data);  
      this.receiveMessage.emit(data);  
    });  
  }
}


  }  

在 IIS Express 上使用“ http://localhost:59235/ChatHub ”一切正常。当我使用“ http://localhost/MyCoreAPI/ChatHub ”切换到本地 IIS 时,出现错误。

标签: .netasp.net-core.net-coresignalr

解决方案


您能否检查是否在 IIS 中启用了 WebSockets 协议。

“打开或关闭 Windows 功能” -> Internet 信息服务 -> 万维网服务 -> 应用程序开发功能 -> WebSocket 协议


推荐阅读