.Net Core 仅在上传文件时被 CORS 策略错误阻止

Posted

技术标签:

【中文标题】.Net Core 仅在上传文件时被 CORS 策略错误阻止【英文标题】:.Net Core blocked by CORS policy error only when uploading a file 【发布时间】:2021-01-19 03:20:31 【问题描述】:

上传文件时需要做一些不同的事情吗?除了上传文件的位置外,其他所有调用(Axios/Vue put)都可以正常工作。它从 example.com 到 api.example.com。在本地访问不同的端口时一切正常。

配置服务:

services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
            
                builder.AllowAnyOrigin()
                       .AllowAnyMethod()
                       .AllowAnyHeader()
                       .SetIsOriginAllowedToAllowWildcardSubdomains();
                       //.WithOrigins("http://*.example.com"); //tried adding, nothing works when it's here
            ));

配置:

app.UseCors("CorsPolicy");

还有控制器:

[ApiController]
[EnableCors("CorsPolicy")]  
public class MyController : ControllerBase 
Public Model Put([FromForm] ICollection<IFormFile> files, [FromForm] string jsonString)

浏览器输出:

Access to XMLHttpRequest at 'http://api.example.com/api/YourKnowledge' from origin 'http://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Request URL: http://api.example.com/api/YourKnowledge
Referrer Policy: strict-origin-when-cross-origin
Date: Sat, 03 Oct 2020 19:58:42 GMT
Server: Microsoft-IIS/10.0
Transfer-Encoding: chunked
X-Powered-By: ASP.NET
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 10219
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryvIG7idij6Og7BH8r
Host: api.example.com
Origin: http://example.com
Referer: http://example.com/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (Khtml, like Gecko) Chrome/85.0.4183.121 Safari/537.36
files: (binary)
jsonString: 

最后一点,我确实找到了这个Asp.Net Core API CORS policy error only in file upload,但我不会只上传图片。确实尝试将其设置为测试,但没有任何作用。

【问题讨论】:

【参考方案1】:

我认为您不能使用 [FromForm] 添加两个参数 (我知道这是至少在 [FromBody] 中的规则)。 请让我知道有效

【讨论】:

以上是关于.Net Core 仅在上传文件时被 CORS 策略错误阻止的主要内容,如果未能解决你的问题,请参考以下文章