Search code examples
c#amazon-s3aws-sdk-net

How to use Contabo S3 storage with AWS S3 SDK for C#?


I'm using the contabo S3 storage to integrate using AWS S3 SDK for C#. I've used the ServiceUrl as https://eu2.contabostorage.com/

Below is the sample source code I've used for client configuration.

AWSConfigsS3.UseSignatureVersion4 = false;
AmazonS3Client S3Client = new AmazonS3Client(Constants.AWSAccessKey, Constants.AWSSecretKey,
              new AmazonS3Config
                 {
                     ServiceURL = Constants.AWSServiceUrl,
                 });
PutObjectRequest request = new PutObjectRequest
{
    BucketName = Constants.AWSBucketName,
    Key = fileName,
    ContentType = "image/jpg"
};
using (var stream = new MemoryStream(DependencyService.Get<IMediaService>().ResizeImage(file.Path, 1024, 1024)))
{
    request.InputStream = stream;
    PutObjectResponse objectResponse = await S3Client.PutObjectAsync(request);
    return fileName;
}

When I run it, I always get exception as "No such host". I've also tried different region and signature version but the same error is coming. What can I do to make it working?


Solution

  • [HttpPost("upload_file")]
    public async Task<ActionResult> UploadFile(IFormFile file)
    {
        string url = "";
    
        try
        {
            var accessKey = "xxxx";
            var secretKey = "xxxx";
            var bucketName = "xxxx";
    
            AmazonS3Config config = new AmazonS3Config();
            config.ServiceURL = "https://eu2.contabostorage.com";
            config.DisableHostPrefixInjection = true;
            config.ForcePathStyle = true;
    
            AmazonS3Client s3Client = new AmazonS3Client(
                    accessKey,
                    secretKey,
                    config
                    );
    
            ListBucketsResponse response = await s3Client.ListBucketsAsync();
    
            using (var newMemoryStream = new MemoryStream())
            {
                file.CopyTo(newMemoryStream);
                PutObjectRequest request = new PutObjectRequest();
                request.BucketName = bucketName;
                request.Key = file.FileName;
                request.ContentType = file.ContentType;
                request.InputStream = newMemoryStream;
                await s3Client.PutObjectAsync(request);
    
                GetPreSignedUrlRequest requestGet = new GetPreSignedUrlRequest();
                requestGet.BucketName = bucketName;
                requestGet.Key = file.FileName;
                requestGet.Expires = DateTime.Now.AddHours(1);
                requestGet.Protocol = Protocol.HTTPS;
                url = s3Client.GetPreSignedURL(requestGet);
            }
        }
        catch (Exception ex)
        {
            return StatusCode(500, Utils.errorMessage(ex));
        }
        return Ok(url);
    }