首页 > 解决方案 > 无法在 API 控制器的“HttpGet”方法中使用 Web 套接字发送数据

问题描述

[ASP.NET] 无法在 API 控制器的“HttpGet”方法中使用 Web 套接字发送数据。\

提示:中文只是翻译,你不必关心它。
:中文翻译提示,你不需要关心他们

后端代码
代码

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;

namespace Null.SimpleFishing.Controllers.WS
{
    [Route("api/[controller]")]
    [ApiController]
    public class WSController : ControllerBase
    {
        [HttpGet]
        public async void Get()
        {
            if (HttpContext.WebSockets.IsWebSocketRequest)
            {
                using (WebSocket webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync())
                {
                    await Echo(HttpContext, webSocket);
                }
            }
            else
            {
                Response.StatusCode = StatusCodes.Status400BadRequest;
            }
        }
        private async Task Echo(HttpContext context, WebSocket webSocket)
        {
            var buffer = new byte[1024 * 4];
            WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            while (!result.CloseStatus.HasValue)
            {
                await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);

                result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            }
            await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);   # exception here
        }
    }
}

前端代码
前端代码

var ws = new WebSocket("ws://localhost:31137/api/ws");  // front end logic is just create a WebSocket (前端逻辑仅仅是创建一个 WebSocket)

异常:
异常:

System.Net.WebSockets.WebSocketException (0x80004005):远端没有完成关闭握手就关闭了WebSocket连接。---> System.ObjectDisposedException:无法写入响应正文,响应已完成。对象名称:'HttpResponseStream'。

但是,如果我在 'Startup.cs' 中编写代码,并使用“app.Use(processor);”,它会很好地工作。
但是,如果我在 'Startup.cs' 中使用这些代码,然后使用“app .Use(逻辑代码);",就不会出现任何问题。
这些代码来自 ASP.NET Core 中的MSDOCS WebSocket
这些代码来自微软文档 ASP.NET Core 中的 Socket

MSDOCS 表示:“使用 WebSocket 时,必须在连接期间保持中间件管道运行。如果在中间件管道结束后尝试发送或接收 WebSocket 消息,可能会收到如下异常:”
微软文档写有:“WebSocket 时,“必须”在连接期间保持中间件管道运行。这个,,,但是我不知道怎么解决。
有可能是因为这个,,,我可是不知道怎么解决</p>

标签: c#asp.netasp.net-corewebsocket

解决方案



推荐阅读