简体   繁体   中英

Task was cancelled exception when uploading file to S3 bucket using AWS .NET SDK?

I have WebApi method in Asp.Net Core 2 app which's receiving file from Angular in base64 format . I need these files to be stored on AWS S3 Bucket , I found the code on amazon official docs but it's not working for me.

I'm getting A task was cancelled exception after few seconds.

Here's my code:

public async Task UploadFileAsync(string base64Image)
{
    try
    {
        var fileTransferUtility = new TransferUtility(_s3Client);

        var image = Convert.FromBase64String(base64Image);
        MemoryStream memStream = new MemoryStream();
        BinaryFormatter binForm = new BinaryFormatter();
        memStream.Write(image, 0, image.Length);
        memStream.Seek(0, SeekOrigin.Begin);

        await fileTransferUtility.UploadAsync(memStream, BucketName, KeyName);
        Debug.WriteLine("Upload completed");
    }
    catch (AmazonS3Exception e)
    {
        Debug.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message);
    }
    catch (Exception e)
    {
        Debug.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
    }

}

Any idea?

I'm not aware how things work in Angular but in regular http request coming to asp.net core api task can be cancelled for couple of reasons:

  1. Timeout (100 sec by default)
  2. Executing async method and not awaiting it
  3. Executing async void method
  4. Running job in different task/thread and not waiting it to complete

Actually 2-4 are same thing: executing job as fire-and-forget. The original task finishing and DI disposes all created types and _s3Client, I believe, one of them. That causes all work started on _s3Client to be cancelled.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM