对于特定大小的文件,Angular文件上传时没有“Access-Control-Allow-Origin”标头错误

时间:2017-11-02 17:40:47

标签: c# asp.net angular asp.net-web-api

我目前正在从Angular前端上传文件到.NET Web API。

uploadFile(file: File, customerId: number) {
  var formData: FormData = new FormData();
  formData.append('file', file, file.name);
  var headers = new HttpHeaders().set('Accept', 'application/json');
  var options = { headers: headers, reportProgress: true };

  const req = new HttpRequest('POST', 'customers/' + customerId + '/fileupload', formData, options)
  return this.http.request(req);
} 

接收此帖子的Web API路由。

[HttpPost]
[Route("{customerId}/fileUpload")]
public IHttpActionResult UploadFiles(int customerId)
{
    if (HttpContext.Current.Request.Files.Count > 0) 
    {
        _fileService.UploadFile(customerId, HttpContext.Current.Request.Files[0]);
        return Ok("Files Successfully Uploaded");
    } 
    else 
    {
        return Ok("0 Files Uploaded");
    }
}

当我发布一个30,000,000字节(~30mb)或更少的文件时,一切都按预期工作,但由于某种原因,当文件较大时,我收到错误:

POST http://localhost:53319/customers/116/fileupload/Production 404 (Not Found)
Failed to load http://localhost:53319/customers/116/fileupload/Production: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 404.

对于我的情况,我需要能够上传最高10 Gbs的文件。有谁知道为什么我的大小超过一定大小的文件会出现此错误以及如何修复它?

我已经对此进行了一些研究,我发现所有内容都是将以下内容添加到Web.config文件中,但尚未解决问题。

<system.web>
  <httpRuntime maxRequestLength="2147483647" />
</system.web>

1 个答案:

答案 0 :(得分:1)

请尝试这种web.config或至少那个requestLimits部分。这来自.Net Core项目,因此语法可能会有所不同。

https://github.com/JanneHarju/MultiSourcePlayList/blob/cbbe3460d107cd07d01ee80e0693f905a295f392/web.config#L11

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <security>
        <requestFiltering>
            <requestLimits maxAllowedContentLength="524288000"/>
        </requestFiltering>
    </security>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
    </handlers>
    <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false"/>
  </system.webServer>
</configuration>

以下是有关它的一些文档https://docs.microsoft.com/en-us/iis/configuration/system.webserver/security/requestfiltering/requestlimits/

  

默认值为30000000,约为28.6MB。