# FastAPI HTTP异常: 422 不可处理的实体

- **ID:** `python/fastapi-missing-content-type`
- **领域:** python
- **类别:** network_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

FastAPI请求体为JSON但缺少Content-Type头，导致验证失败。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.x | active | — | — |

## 解决方案

1. **确保客户端发送正确的Content-Type头** (95% 成功率)
   ```
   requests.post(url, json={'key': 'value'})  # 自动设置Content-Type: application/json
   ```
2. **使用中间件检查并设置默认Content-Type** (85% 成功率)
   ```
   from starlette.middleware.base import BaseHTTPMiddleware; class ContentTypeMiddleware(BaseHTTPMiddleware): async def dispatch(self, request, call_next): if not request.headers.get('Content-Type'): request.headers.__dict__['_list'].append(('content-type', 'application/json')); return await call_next(request)
   ```

## 无效尝试

- **忽略Content-Type头，期望框架自动检测** — FastAPI严格依赖Content-Type头。 (90% 失败率)
- **在路由中使用request.json()手动解析** — 仍然需要Content-Type头。 (80% 失败率)
