huangxiaoqiang
2025-05-19 051aa9a0e7f58af6665fb4526e42cf8060fbaa05
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
 
namespace WebSocket
{
    public class WebSocketMiddleware
    {
        private readonly RequestDelegate _next;
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="next"></param>
        /// <param name="actionPathName">目标路径</param>
        public WebSocketMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        /// <summary>
        /// 中间件调用
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext httpContext)
        {
            try
            {
                var socket = await httpContext.WebSockets.AcceptWebSocketAsync();
                await new WebSocketHelper().WebSocketReceive(socket);
            }
            catch (Exception)
            {
            }
            await _next(httpContext);
        }
    }
}