从源 'https://app.example.com' 对 'https://api.example.com' 的 XMLHttpRequest 访问已被 CORS 策略阻止:预检请求的响应未通过访问控制检查:它没有 HTTP 正常状态。
Access to XMLHttpRequest at 'https://api.example.com' from origin 'https://app.example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
ID: dotnet/aspnetcore-cors-preflight-failure
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| dotnet 6.0 | active | — | — | — |
| dotnet 8.0 | active | — | — | — |
| ASP.NET Core 6.0 | active | — | — | — |
| ASP.NET Core 8.0 | active | — | — | — |
根因分析
CORS 预检 OPTIONS 请求失败,因为服务器未返回 200 状态或缺少必需的 CORS 头(例如 Access-Control-Allow-Origin)。
English
CORS preflight OPTIONS request fails because the server does not respond with a 200 status or missing required CORS headers (e.g., Access-Control-Allow-Origin).
官方文档
https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-8.0解决方案
-
Configure ASP.NET Core CORS middleware to handle preflight requests correctly. Example in Program.cs:
-
If using custom middleware, ensure OPTIONS requests return 200 with appropriate headers before other middleware.
-
For development, use a proxy in the client app (e.g., in React or Angular) to avoid CORS entirely.
无效尝试
常见但无效的做法:
-
95% 失败
Only works locally; production browsers enforce CORS, breaking the app for real users.
-
80% 失败
Preflight still fails if the server returns 404 or 500 for OPTIONS; the header alone is not enough.
-
85% 失败
CORS with credentials requires specific headers (Access-Control-Allow-Credentials: true) and cannot use wildcard origin.