# 断言错误：中间件必须在路由之前添加

- **ID:** `python/starlette-middleware-order`
- **领域:** python
- **类别:** config_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

在 Starlette 中，尝试在路由已定义后添加中间件，导致断言失败。

## 版本兼容性

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

## 解决方案

1. **** (90% 成功率)
   ```
   app = Starlette(routes=routes, middleware=[Middleware(AuthenticationMiddleware)])
   ```
2. **** (85% 成功率)
   ```
   app = Starlette()
app.add_middleware(AuthenticationMiddleware)
app.router.routes = routes
   ```

## 无效尝试

- **** — 虽然能解决，但代码冗余且不优雅。 (70% 失败率)
- **** — 中间件功能（如认证）将失效。 (80% 失败率)
