且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SignalR .Net Core 3.1 Web应用程序无法在本地IIS上运行

更新时间:2023-02-15 21:58:02

能否检查IIS中是否启用了WebSockets协议.

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

Trying to create a chat based on an online example using ASP.Net Core 3.1 and Angular.

The following works perfectly well on IIS Express, but not on local IIS.

Error Message: WebSocketTransport.js:85 WebSocket connection to 'ws://localhost/MyCoreAPI/ChatHub' failed: Error during WebSocket handshake: Unexpected response code: 400

Startup:

    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");
        });
    }

ChatHub:

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

Client:

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);  
    });  
  }
}


  }  

On IIS Express using 'http://localhost:59235/ChatHub' everything works. When I switch to local IIS using 'http://localhost/MyCoreAPI/ChatHub' I get the error.

Can you check if WebSockets Protocol is enabled in IIS.

"Turn Windows features on or off" -> Internet Information Services ->World Wide Web Services -> Application Development Features -> WebSocket Protocol