获取桶策略

GetBucketPolicy操作用于获取bucket的policy,policy配置功能可以使用户根据需求更精确地定义bucket的访问策略。bucket的所有者可以查看bucket的policy信息。

代码示例:

using System;
using System.Threading.Tasks;
using Amazon.Runtime;
using Amazon.S3;
using Amazon.S3.Model;

namespace DotNetSDK.BucketOperation
{
    public class GetBucketPolicyExample
    {
        public static async Task GetBucketPolicy()
        {
            var accessKey = "YOUR_ACCESS_KEY";
            var secretKey = "YOUR_SECRET_KEY";
            var endpoint = "YOUR_ENDPOINT";
            var bucketName = "EXAMPLE_BUCKET";
            try
            {
                var credentials = new BasicAWSCredentials(accessKey, secretKey);
                var conf = new AmazonS3Config
                {
                    ServiceURL = endpoint
                };
                var s3Client = new AmazonS3Client(credentials, conf);
                var getBucketPolicyRequest = new GetBucketPolicyRequest()
                {
                    BucketName = bucketName
                };

                var result = await s3Client.GetBucketPolicyAsync(getBucketPolicyRequest);
                if (result.HttpStatusCode != System.Net.HttpStatusCode.OK)
                {
                    Console.WriteLine("fail to get policy of bucket {0}, HttpStatusCode:{1}, ErrorCode:{2}.", bucketName, (int) result.HttpStatusCode, result.HttpStatusCode);
                    return;
                }

                Console.WriteLine("the policy of bucket {0} is: {1}.", bucketName, result.Policy);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}

GetBucketPolicyRequest可设置的参数如下:

参数 类型 说明 是否必要
BucketName string bucekt的名称。

GetBucketPolicyOutput返回的结果如下:

属性名 类型 说明
Policy string JSON格式的bucekt策略信息。

响应结果:

HTTP状态码 响应码 描述
200 OK 操作成功。
403 Forbidden 用户没有权限执行操作。
404 NotFound 操作指定的bucekt或者bucekt策略不存在。