# Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware: CORS 协议不允许预检请求包含请求体。

- **ID:** `dotnet/aspnet-core-cors-preflight-failure`
- **领域:** dotnet
- **类别:** protocol_error
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

ASP.NET Core CORS 中间件拒绝包含请求体的预检 OPTIONS 请求，因为违反了 CORS 规范。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.1 | active | — | — |
| 5.0 | active | — | — |
| 6.0 | active | — | — |
| 7.0 | active | — | — |
| 8.0 | active | — | — |

## 解决方案

1. ```
   确保客户端在 OPTIONS 预检请求中不发送请求体。对于 fetch API，避免在 OPTIONS 中设置 body。示例：fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) 并让浏览器处理无请求体的预检。
   ```
2. ```
   配置 CORS 中间件以提前处理 OPTIONS 请求，在 Startup.cs 或 Program.cs 中将 app.UseCors() 放在 app.UseRouting() 和 app.UseEndpoints() 之前。
   ```
3. ```
   使用自定义中间件在 CORS 中间件运行之前读取并丢弃 OPTIONS 请求的请求体。示例：app.Use(async (context, next) => { if (context.Request.Method == "OPTIONS") { context.Request.Body = Stream.Null; } await next(); });
   ```

## 无效尝试

- **Modifying the CORS policy to allow all headers and methods without addressing the body issue** — CORS policy configuration does not affect the protocol-level restriction on preflight request bodies. (90% 失败率)
- **Disabling CORS middleware entirely in development** — Disabling CORS removes cross-origin protection and may cause security issues; also does not fix the root cause for production. (70% 失败率)
- **Adding custom middleware to ignore the body on OPTIONS requests** — Custom middleware may not run before CORS middleware in the pipeline, or may interfere with other request handling. (60% 失败率)
