python
config_error
ai_generated
true
AssertionError: Cannot add middleware after an application has started
ID: python/starlette-middleware-order-response-headers
80%Fix Rate
84%Confidence
0Evidence
2024-08-27First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 0.30+ | active | — | — | — |
Root Cause
app.add_middleware() was called after the ASGI app had already started serving (e.g., inside a route or after TestClient instantiation).
generic中文
在 ASGI 应用已经开始提供服务后调用了 app.add_middleware()(例如在路由内或 TestClient 实例化之后)。
Workarounds
-
95% success
app = FastAPI() app.add_middleware(CORSMiddleware, allow_origins=['*']) # then define routes
-
90% success
def create_app(): app = FastAPI() app.add_middleware(...) return app
Dead Ends
Common approaches that don't work:
-
85% fail
The middleware is never added; headers/logging silently missing.
-
90% fail
Startup fires after the middleware stack is built; assertion still raised.