Startup.cs的Configure中添加了
app.UseWebSockets(new WebSocketOptions
{
KeepAliveInterval = TimeSpan.FromSeconds(60),
ReceiveBufferSize = 8 * 1024
});
app.UseMiddleware<Services.WebSocketHelper>();
在WebSocketHtlper中代码如下:
public async Task Invoke(HttpContext context)
{
if (!context.WebSockets.IsWebSocketRequest)
{
await _next.Invoke(context);
return;
}
CancellationToken ct = context.RequestAborted;
var currentSocket = await context.WebSockets.AcceptWebSocketAsync();
string socketId = Guid.NewGuid().ToString();
if (context.Request.Query.ContainsKey("sid"))
{
socketId = context.Request.Query["sid"].ToString();
}
if (!_sockets.ContainsKey(socketId))
{
_sockets.TryAdd(socketId, currentSocket);
}
Handle(ct, socketId, currentSocket);
}
前端通过new WebSocket(uri)建立WebSocket连接时,请求头如下:
Connection:Upgrade
Host:localhost:44365
Origin:http://localhost:1862
Pragma:no-cache
Sec-WebSocket-Extensions:permessage-deflate; client_max_window_bits
Sec-WebSocket-Key:0ejzra2kkron2xF16WkyWg==
Sec-WebSocket-Version:13
Upgrade:websocket
但在后端判断是否是WebSocket请求时,context.WebSockets.IsWebSocketRequest始终返回False。
我的调试环境是Win7+vs2019+Chrome