# System.InvalidOperationException: 必须在中间件管道中先调用 'UseRouting' 方法，然后才能调用 'UseEndpoints'。

- **ID:** `dotnet/aspnet-core-middleware-ordering`
- **领域:** dotnet
- **类别:** config_error
- **验证级别:** ai_generated
- **修复率:** 95%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 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 | — | — |

## 解决方案

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.
   ```

## 无效尝试

- **** — Removing UseRouting entirely breaks endpoint routing for MVC or minimal APIs. (95% 失败率)
- **** — Adding duplicate UseRouting calls causes ambiguous routing state. (90% 失败率)
- **** — Moving UseEndpoints before UseRouting in the same method doesn't fix order in different Configure blocks. (85% 失败率)
