O versionamento aplica-se a todos os objetos em um bucket e permite recuperar versões anteriores caso sejam sobrescritas ou excluídas acidentalmente.
Um bucket pode estar em um dos seguintes estados de versionamento: desativado (padrão), ativado ou suspenso. Para obter mais informações sobre versionamento, consulte Versionamento.
Observações
Este tópico usa o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
Este tópico demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação via Security Token Service (STS), consulte Inicialização (C# SDK V1).
Para definir o estado de versionamento de um bucket, você deve ter a permissão
oss:PutBucketVersioning. Para consultar informações sobre o estado de versionamento de um bucket, você deve ter a permissãooss:GetBucketVersioning. Para obter mais informações, consulte Conceder uma política de acesso personalizada a um usuário RAM.
Configurar o versionamento de um bucket
O código a seguir mostra como ativar ou suspender o versionamento de um bucket.
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// 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 name of the bucket. Example: examplebucket.
var bucketName = "examplebucket";
// 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
{
// Set the versioning status of the bucket to Enabled.
client.SetBucketVersioning(new SetBucketVersioningRequest(bucketName, VersioningStatus.Enabled));
Console.WriteLine("Create bucket Version succeeded");
}
catch (Exception ex)
{
Console.WriteLine("Create bucket Version failed. {0}", ex.Message);
}
Consultar o status de versionamento de um bucket
O código a seguir mostra como consultar o estado de versionamento de um bucket.
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// 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 name of the bucket. Example: examplebucket.
var bucketName = "examplebucket";
// 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 versioning status of the bucket.
var result = client.GetBucketVersioning(bucketName);
Console.WriteLine("Get bucket:{0} Version succeeded ", bucketName);
Console.WriteLine("bucket version status: {0}", result.Status);
}
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);
}
catch (Exception ex)
{
Console.WriteLine("Failed with error info: {0}", ex.Message);
}
Listar as versões de todos os objetos em um bucket
O código a seguir mostra como listar todas as versões de objetos, incluindo marcadores de exclusão, em um bucket específico.
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// 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 name of the bucket. Example: examplebucket.
var bucketName = "examplebucket";
// 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
{
ObjectVersionList result = null;
var request = new ListObjectVersionsRequest(bucketName);
do {
result = client.ListObjectVersions(request);
Console.WriteLine("ListObjectVersions succeeded");
// View the versions of all listed objects.
foreach (var objectversion in result.ObjectVersionSummaries)
{
Console.WriteLine("objectversion key: {0}; objectversion versionid: {1}", objectversion.Key, objectversion.VersionId);
}
// View the versions of all listed delete markers.
foreach (var deletemarker in result.DeleteMarkerSummaries)
{
Console.WriteLine("deletemarker key: {0}; deletemarker versionid: {1}", deletemarker.Key, deletemarker.VersionId);
}
request.KeyMarker = result.NextKeyMarker;
request.NextVersionIdMarker = result.NextVersionIdMarker;
} while (result.IsTruncated)
}
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);
}
catch (Exception ex)
{
Console.WriteLine("Failed with error info: {0}", ex.Message);
}
Referências
Para obter mais informações sobre a operação de API usada para configurar o versionamento de um bucket, consulte PutBucketVersioning.
Para obter mais informações sobre a operação de API usada para consultar o status de versionamento de um bucket, consulte GetBucketVersioning.