我有这段代码用于处理大文件(这是用于上传大型 CSV 文件):
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);
}
internal async Task ProcessBulkUpload(CsvProcessedResponseDto<OrderCsvResponseDto> content)
{
// do some processing...
}
有 web.config 设置可以增加文件上传的允许时间,这可能会有所帮助:How to increase the max upload file size in ASP.NET?
如果您的请求超过允许的最大超时时间,数据将不会按预期返回给您的调用者!
如果你想从 C# 中执行“即发即弃”代码,你可以这样做:
public static void FireAndForget(this Task task)
{
Task.Run(async() => await task).ConfigureAwait(false);
}
Javascript:
xhr.onreadystatechange = function() { xhr.abort(); }
AngularJS:
var defer = $q.defer();
$http.get('/example', { timeout: defer.promise }).success(callback);
// [...]
defer.resolve();
一些针对 Js 的 async/await 技巧:http://2ality.com/2016/10/async-function-tips.html