dotnet config_error ai_generated true

System.InvalidOperationException: The 'UseRouting' method must be called before 'UseEndpoints' in the middleware pipeline.

ID: dotnet/aspnet-core-middleware-ordering

Also available as: JSON · Markdown · 中文
95%Fix Rate
88%Confidence
1Evidence
2023-01-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
ASP.NET Core 3.1.x active
ASP.NET Core 5.0.x active
ASP.NET Core 6.0.x active
ASP.NET Core 7.0.x active
ASP.NET Core 8.0.x active

Root Cause

ASP.NET Core middleware pipeline ordering violation: UseRouting must precede UseEndpoints, but they are reversed or missing.

generic

中文

ASP.NET Core 中间件管道排序违规:UseRouting 必须在 UseEndpoints 之前调用,但顺序颠倒或缺失。

Official Documentation

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-8.0#order

Workarounds

  1. 95% success Ensure middleware order: app.UseRouting(); app.UseEndpoints(endpoints => { ... });
    Ensure middleware order: app.UseRouting(); app.UseEndpoints(endpoints => { ... });
  2. 90% success Use app.UseRouting() and app.UseEndpoints() in the same Configure method, not split across partial classes.
    Use app.UseRouting() and app.UseEndpoints() in the same Configure method, not split across partial classes.
  3. 85% success For minimal APIs, ensure app.MapGet/Post are called after UseRouting and before UseEndpoints.
    For minimal APIs, ensure app.MapGet/Post are called after UseRouting and before UseEndpoints.

中文步骤

  1. Ensure middleware order: app.UseRouting(); app.UseEndpoints(endpoints => { ... });
  2. Use app.UseRouting() and app.UseEndpoints() in the same Configure method, not split across partial classes.
  3. For minimal APIs, ensure app.MapGet/Post are called after UseRouting and before UseEndpoints.

Dead Ends

Common approaches that don't work:

  1. 95% fail

    Removing UseRouting entirely breaks endpoint routing for MVC or minimal APIs.

  2. 90% fail

    Adding duplicate UseRouting calls causes ambiguous routing state.

  3. 85% fail

    Moving UseEndpoints before UseRouting in the same method doesn't fix order in different Configure blocks.