# AssertionError: 应用启动后无法添加中间件

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

## 根因

在 ASGI 应用已经开始提供服务后调用了 app.add_middleware()（例如在路由内或 TestClient 实例化之后）。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 0.30+ | active | — | — |

## 解决方案

1. **** (95% 成功率)
   ```
   app = FastAPI()
app.add_middleware(CORSMiddleware, allow_origins=['*'])
# then define routes
   ```
2. **** (90% 成功率)
   ```
   def create_app():
    app = FastAPI()
    app.add_middleware(...)
    return app
   ```

## 无效尝试

- **** — The middleware is never added; headers/logging silently missing. (85% 失败率)
- **** — Startup fires after the middleware stack is built; assertion still raised. (90% 失败率)
