尝试使用 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时,出现错误。
你能检查一下IIS中是否启用了WebSockets协议吗?
"打开或关闭 Windows 功能" -> 互联网信息服务 ->万维网服务 -> 应用程序开发功能 -> WebSocket 协议