c# - 无法在 API 控制器的“HttpGet”方法中使用 Web 套接字发送数据
问题描述
[ASP.NET] 无法在 API 控制器的“HttpGet”方法中使用 Web 套接字发送数据。\
- [ASP.NET] 无法在 API 控制器的 'HttpGet 方法中使用 web socket 发送数据</li>
提示:中文只是翻译,你不必关心它。
:中文翻译提示,你不需要关心他们
后端代码
代码
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>
解决方案
推荐阅读
- repository - E:存储库“http://dl.bintray.com/aluxian/deb stable Release”没有Release文件
- oracle - 对异常类型有一些混淆
- python - 如何在 python 中通过服务器发送屏幕截图但以 1024 为单位发送屏幕截图?
- sql - 获取每个视频的评论和每个视频频道的评论总数
- r - 如何将 SPSS 日期转换公式应用于多个变量?
- php - 为什么 ldap_errno() 在这里提供连接?
- c++ - C++ - 在 foreach 中复制向量给出“没有匹配的函数来调用 std::vector
::push_back(std::vector &)" - flutter - 以编程方式在 AlertDialog 内的 flutter_material_color_picker 中设置颜色
- php - laravel刀片部分视图错误中的未定义变量
- ionic-framework - Ionic 4 侧边菜单未在三星浏览器中关闭