AWS开发工具包.Net API - 在脚本中运行命令?

时间:2017-11-29 03:01:47

标签: c# .net amazon-s3 aws-sdk

使用AWS SDK .NET API,有没有办法发送AWS CLI命令?

我需要定期“刷新”Bucket的缓存控制策略(以及该存储桶中的所有图像),并且我想从.Net C#Web应用程序触发/运行它。

脚本如下:

 aws s3 cp s3://mybucket/ s3://mybucket/ --recursive --metadata-directive REPLACE \ --expires 2034-01-01T00:00:00Z --acl public-read --cache-control max-age=2592000,public

我从这个解决方案得到的: Set cache-control for entire S3 bucket automatically (using bucket policies?)

有没有办法通过API将此命令发送到亚马逊?我是一个新手,所以实际的代码将是有用的(即如何验证和发送它)。如果不是API,有没有办法将其作为REST查询发送?

1 个答案:

答案 0 :(得分:0)

嗯,为了将来的参考,我最终得到的似乎是在工作

string accessKeyID = "ACCESKEYID";
string secretAccessKey = "SECRETACCESSKEY";

using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKeyID, secretAccessKey))
{

    try
    {

        //First, get a list of all objects in the bucket.  We need to go through them one at a time.
        ListObjectsRequest listobjectsrequest = new ListObjectsRequest();
        listobjectsrequest = new ListObjectsRequest();
        listobjectsrequest.BucketName = "mybucketname";

        ListObjectsResponse listobjectresponse = client.ListObjects(listobjectsrequest);

        // Process each item
        foreach (S3Object entry in listobjectresponse.S3Objects)
        {
            //Get the object so we can look at the headers to see if it already has a cache control header
            GetObjectRequest getobjectrequest = new GetObjectRequest
            {
                BucketName = listobjectsrequest.BucketName,
                Key = entry.Key,

            };

            GetObjectResponse object1 = client.GetObject(getobjectrequest);

            string cacheControl1 = object1.Headers["Cache-Control"] ?? "none";

            //If no cache control header, then COPY the object to ITSELF but add the headers that we need
            if (cacheControl1 != "none")
            {

                CopyObjectRequest copyobjectrequest = new CopyObjectRequest
                {
                    SourceBucket = listobjectsrequest.BucketName,
                    SourceKey = entry.Key,
                    DestinationBucket = listobjectsrequest.BucketName,
                    DestinationKey = entry.Key,
                    Directive = S3MetadataDirective.REPLACE, //Required if we will overwrite headers
                    CannedACL = S3CannedACL.PublicRead //Need to set to public so it can be read

                };

                copyobjectrequest.AddHeader("Cache-Control", "max-age=31536000,public");
                CopyObjectResponse copyobjectresponse = client.CopyObject(copyobjectrequest);

            }


        }



    }
    catch (AmazonS3Exception amazonS3Exception)
    {
        Console.WriteLine(amazonS3Exception.Message, amazonS3Exception.InnerException);
    }

}