首先,给出 MSDN 的 websocket 实现方式 https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/websockets?view=aspnetcore-3.0

不过一般情况下,我们不希望把业务逻辑放到 startup.cs 类进行实现

我们先新增个 websocket handler 类进行基本的请求处理

    public class WebSocketHandler
    {
        public const int BufferSize = 1024;
        WebSocket socket;

        WebSocketHandler(WebSocket socket)
        {
            this.socket = socket;
        }

        //ws消息应答处理
        async Task EchoLoop()
        {
            var buffer = new byte[BufferSize];
            var seg = new ArraySegment(buffer);
            while (this.socket.State == WebSocketState.Open)
            {
                //ws请求消息监听
                var incoming = await this.socket.ReceiveAsync(seg, CancellationToken.None);
                //可将消息转为字符串做自己的业务处理,不如转发给目标 websocket 连接
                string recvMsg = Encoding.UTF8.GetString(seg.Array, 0, incoming.Count);
                try
                {
                    //设置当收到请求时,返回的ws消息
                    var outgoing = Encoding.UTF8.GetBytes("succeed");
                    //这里是将消息返回给请求方的ws连接
                    await this.socket.SendAsync(outgoing, WebSocketMessageType.Text, true, CancellationToken.None);
                }
                catch (Exception e)
                {
                    //异常处理
                    var outgoing = Encoding.UTF8.GetBytes(e.Message);
                    await this.socket.SendAsync(outgoing, WebSocketMessageType.Text, true, CancellationToken.None);
                }
            }
        }

        //wx接收方法
        static async Task Acceptor(HttpContext hc, Func n)
        {
            if (!hc.WebSockets.IsWebSocketRequest)
                return;
            var socket = await hc.WebSockets.AcceptWebSocketAsync();

            var h = new WebSocketHandler(socket);
            await h.EchoLoop();
        }


        // 路由绑定处理
        public static void Map(IApplicationBuilder app)
        {
            app.UseWebSockets();
            app.Use(WebSocketHandler.Acceptor);
        }
    }

然后在 startup.cs 类,Configure方法中进行使用

 app.UseMvc();
 app.Map("/ws", SocketHandler.Map);//这里定义ws请求的url,ws://127.0.0.1/ws

为了方便测试,我们可以找一个 websocket 在线工具进行测试

测试通过,说明 ws 服务已经正常启动