通过 JSON 将大字符串发送到服务器,并出现 ASP.NET 5 - CORS 错误

本文关键字:ASP NET 错误 CORS JSON 字符串 服务器 通过 | 更新日期: 2023-09-27 18:30:26

我在将文件作为字节数组 json 字符串发送到服务器时遇到问题。当文件相对较小时:最多 2MB 左右,那么它可以正常工作,但如果文件像4MB,那么请求会抛出错误(它甚至没有到达后端的控制器)。

错误:

XMLHttpRequest cannot load http://localhost:61416/api/organisationdocuments/.
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:51080' is therefore not allowed access. 
The response had HTTP status code 404.

在我有startup.cs

 // Add CORS support.
        services.AddCors(options =>
        {
            options.AddPolicy("AAPolicy", policyBuilder =>
                policyBuilder
                    .AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials()
                );
        });

在前端我使用angularjs.该方法如下所示:

this.addFile = function (file) {
            return $http.post(fileApi, file);
        };

我在前面调试了它,它看起来不错,除了带有字节数组的字符串太大了,有时会挂起我的浏览器。所以正如我提到的,它适用于较小的文件,只适用于较大的文件。它显然必须与文件的重量有关。

我尝试调试后端,但它甚至没有到达控制器,所以没有办法。有什么想法吗?多谢!

编辑:

我的网络配置文件:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <httpRuntime maxRequestLength="10000000" />
  </system.web>
  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="10000000" />
      </requestFiltering>
    </security>
    <handlers>
      <add name="httpPlatformHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" />
    </handlers>
    <httpPlatform processPath="%DNX_PATH%" arguments="%DNX_ARGS%" stdoutLogEnabled="false" startupTimeLimit="3600" />
  </system.webServer>
</configuration>

通过 JSON 将大字符串发送到服务器,并出现 ASP.NET 5 - CORS 错误

将其

添加到您的Web.Config,它将允许您上传最大10MB的内容。(10000000 = 10 MB)

<system.web>
  <httpRuntime maxRequestLength="10000000" />
</system.web>
<system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="10000000" />
      </requestFiltering>
    </security>
</system.webServer>

希望这个帮助

您必须使用块方法来执行此操作或使用流数组

检查此链接