A bucket is a container used to store objects in Object Storage Service (OSS). All objects in OSS are contained in buckets. This topic describes how to query the region of a bucket.
Usage notes
In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS from other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about the regions and endpoints in OSS, see Regions and endpoints.
In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Initialization.
To query the region where a bucket is located, you must have the
oss:GetBucketLocation
permission. For more information, see Attach a custom policy to a RAM user.
Sample code
The following sample code shows how to query the region or location of a bucket:
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Specify the endpoint of a region that is supported by OSS. Example: https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the bucket name.
var bucketName = "yourBucketName";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify parameters as required.
var conf = new ClientConfiguration();
// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// Query the region of the bucket.
var result = client.GetBucketLocation(bucketName);
Console.WriteLine("Get bucket:{0} Info succeeded ", bucketName);
Console.WriteLine("bucket Location: {0}", result.Location);
}
catch (OssException ex)
{
Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
References
For more information about the API operation that you can call to query the region of a bucket, see GetBucketLocation.