python
data_error
ai_generated
true
FastAPI WebSocket 请求验证错误:消息文本应为字符串类型
fastapi.exceptions.WebSocketRequestValidationError: 1 validation error for WebSocket\nmessage -> text\n str type expected (type=value_error.str)
ID: python/fastapi-websocket-json-error
80%修复率
83%置信度
0证据数
2025-05-18首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
WebSocket 消息格式不符合预期。
English
WebSocket 消息格式不符合预期。
解决方案
-
85% 成功率
data = await websocket.receive_text()\n# 手动验证
-
90% 成功率
from pydantic import BaseModel\nclass Message(BaseModel):\n text: str\nmsg = Message.parse_raw(data)
无效尝试
常见但无效的做法:
-
50% 失败
可能忽略验证。
-
80% 失败
导致连接异常。