将 csv 文件上传到网络时出现 502 错误 api

502 error upload csv file to web api

我有一个带有文件上传功能的 Angular5 用户界面。用户点击一个按钮并选择一个文件,该文件被发送到网络api(asp.NET核心)方法进行处理。

这适用于较小的文件,但对于较大的文件,请求超时并出现 502 错误。

我可以看到请求总是在 120 秒时超时。 (注意:我在开发中通过节点托管,在生产中通过 IIS 托管)。

在大文件的情况下,我需要将此超时延长到一个更大的值。我尝试通过多种方式实现这一目标:

  1. 请求 Header - angular 代码中的请求超时。我使用以下代码尝试设置超时 header 值,但它不会影响 120 秒:

    export class AuthTokenInterceptor implements HttpInterceptor {
    
    constructor(private authContext: AuthContext) {
    }
    
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const authHeaderValue = this.authContext.getAuthenticationHeaderValue(req.url);
    
        if (authHeaderValue) {
            const authReq = req.clone({  headers:
              req.headers.set('Authorization', authHeaderValue)
                         .set('Timeout', '100000000000000000') });
    
            return next.handle(authReq);
        }
        return next.handle(req);
    }    }
    
  2. web.config - 我已经尝试将 web.config 文件中的 httpRuntime 超时值设置为以下值(但仍有时间在 120 秒时结束):

  3. 在 IIS 中 - 我尝试在 IIS 中设置 "Limits" 属性 的配置,但仍然超时在 120 秒(当我 运行 通过节点服务器时这没有任何关系)。

有没有人能够在他们的 Angular(2+) 个应用程序请求中修改这 120 秒?

感谢提前指点!

注意:为了完整起见,这是我的 asp.net 核心,用于上传的控制器方法:

[HttpPost("Upload")]
public async Task<IActionResult> UploadAsync(IFormFile file)
{
    // Ensure the file has contents before processing.
    if (file == null || file.Length == 0)
        throw new ApiException("Csv file should not be null", HttpStatusCode.BadRequest)
            .AddApiExceptionResponseDetails(ErrorTypeCode.ValidationError, ErrorCode.BelowMinimumLength, SOURCE); 

    // Ensure the file is not over the allowed limit.
    if (file.Length > (_settings.MaxCsvFileSize * 1024))
        throw new ApiException("Max file size exceeded, limit of " + _settings.MaxCsvFileSize + "mb", HttpStatusCode.BadRequest)
            .AddApiExceptionResponseDetails(ErrorTypeCode.ValidationError, ErrorCode.ExceedsMaximumLength, SOURCE); 

    // Ensure the file type is csv and content type is correct for the file.
    if (Path.GetExtension(file.FileName) != ".csv" || 
        !Constants.CsvAcceptedContentType.Contains(file.ContentType.ToLower(CultureInfo.InvariantCulture)))
            throw new ApiException("Csv content only accepted").AddApiExceptionResponseDetails(ErrorTypeCode.ValidationError, ErrorCode.Invalid, SOURCE);

    // Read csv content.
    var content = await file.ReadCsvAsync<OrderCsvResponseDto>() as CsvProcessedResponseDto<OrderCsvResponseDto>;

    await ProcessBulkUpload(content);

    // Return information about the csv file.
    return Ok(content);
}

注意 - 当我通过 IIS Express 运行 网络 api 然后它超时,我已经 运行 它使用命令主机并且它不会超时 -看起来这可能与某种 IIS 设置有关。由于我正在使用新版本的 ASP.net 核心,网络 api 没有 web.config 文件,但这段代码似乎与 IIS Express 没有任何关系当我 运行 通过它时:

      var host = new WebHostBuilder()
                .UseStartup<Startup>()
                .UseKestrel(o => {

                    o.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(10);
                    o.ShutdownTimeout = TimeSpan.FromMinutes(10);
                    o.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(10);

                })
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseApplicationInsights()
                .Build();

我会 post 在这里,以防其他人遇到我遇到的同样问题。事实证明,IIS Express(或托管 IIS)中的 运行 配置设置覆盖了代码中的任何内容(也许这是因为较新版本的 .net Core 没有 web.config 文件在项目中 - 我不确定)。

无论如何,我通过执行以下步骤解决了这个问题:

在任务栏中打开 IIS Express

单击您 运行 的应用(并希望延长其请求超时)。 单击该应用程序会显示该应用程序的配置文件。双击打开配置文件。

将以下设置应用于 aspNetCore 部分:

requestTimeout="00:20:00"

示例:

   <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" forwardWindowsAuthToken="false" requestTimeout="00:20:00" stdoutLogEnabled="false" />
      <httpCompression>
        <dynamicCompression>
          <add mimeType="text/event-stream" enabled="false" />
        </dynamicCompression>
      </httpCompression>
    </system.webServer>

就是这样!

注意:我在 PaaS ASE 中托管应用程序 - 因此无法在此处直接配置 IIS。我现在的解决方案是将 web.config 文件添加到 api 项目,并在其中应用我的设置。构建过程尊重您已经拥有的 web.config 而不是即时生成一个,它将保留所需的更改。在我的例子中,web.config 看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
    </handlers>
    <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" forwardWindowsAuthToken="false" requestTimeout="00:20:00" stdoutLogEnabled="false" />
  </system.webServer>
</configuration>

希望这对其他人有帮助!