dotnet
protocol_error
ai_generated
true
Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware: CORS 协议不允许预检请求包含请求体。
Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware: The CORS protocol does not allow a preflight request to have a body.
ID: dotnet/aspnet-core-cors-preflight-failure
85%修复率
83%置信度
1证据数
2024-05-01首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.1 | active | — | — | — |
| 5.0 | active | — | — | — |
| 6.0 | active | — | — | — |
| 7.0 | active | — | — | — |
| 8.0 | active | — | — | — |
根因分析
ASP.NET Core CORS 中间件拒绝包含请求体的预检 OPTIONS 请求,因为违反了 CORS 规范。
English
ASP.NET Core CORS middleware rejects a preflight OPTIONS request because it contains a body, which violates the CORS specification.
官方文档
https://learn.microsoft.com/en-us/aspnet/core/security/cors解决方案
-
确保客户端在 OPTIONS 预检请求中不发送请求体。对于 fetch API,避免在 OPTIONS 中设置 body。示例:fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) 并让浏览器处理无请求体的预检。 -
配置 CORS 中间件以提前处理 OPTIONS 请求,在 Startup.cs 或 Program.cs 中将 app.UseCors() 放在 app.UseRouting() 和 app.UseEndpoints() 之前。
-
使用自定义中间件在 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
90% 失败
CORS policy configuration does not affect the protocol-level restriction on preflight request bodies.
-
Disabling CORS middleware entirely in development
70% 失败
Disabling CORS removes cross-origin protection and may cause security issues; also does not fix the root cause for production.
-
Adding custom middleware to ignore the body on OPTIONS requests
60% 失败
Custom middleware may not run before CORS middleware in the pipeline, or may interfere with other request handling.