Todos os produtos
Search
Central de documentação

Object Storage Service:Manage object metadata (OSS SDK for C# 1.0)

Última atualização: Sep 22, 2026

Os objetos armazenados no Object Storage Service (OSS) consistem em chaves, dados e metadados de objeto. Os metadados de objeto descrevem o objeto e incluem cabeçalhos HTTP padrão e metadados de usuário. Ao configurar os cabeçalhos HTTP padrão, é possível criar políticas personalizadas de requisição HTTP, como políticas de cache de objetos e de download forçado. Também é possível configurar metadados de usuário para um objeto a fim de identificar suas finalidades ou atributos.

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 do OSS, use um endpoint interno. Para obter mais informações sobre regiões e endpoints do OSS, consulte Regions and endpoints.

  • Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como usar um domínio personalizado ou autenticar-se com credenciais do Security Token Service (STS), consulte Initialization (C# SDK V1).

  • Para configurar metadados de objeto, é necessária a permissão oss:PutObject. Para consultar metadados de objeto, é necessária a permissão oss:GetObject. Para obter mais informações, consulte Grant a custom policy.

Código de exemplo

O código a seguir exemplifica como configurar, modificar e consultar metadados de objeto:

using Aliyun.OSS;
using Aliyun.OSS.Common;
using Aliyun.OSS.Util;

// 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. 
var bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. 
var objectName = "exampleobject.txt";
// Specify the full path of the local object that you want to upload. By default, if you do not specify the full path of the local object, the local object is uploaded from the path of the project to which the sample program belongs. 
var localFilename = "D:\\localpath\\examplefile.txt";
// 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 the default parameters based on your requirements.
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
{
    using (var fs = File.Open(localFilename, FileMode.Open))
    {
        // Create metadata for the object. You can configure HTTP headers for the object. 
        var metadata = new ObjectMetadata()
        {
            // Specify the content type of the object. 
            ContentType = "text/html",
            // Specify the expiration time of the cache in UTC. 
            ExpirationTime = DateTime.Parse("2025-10-12T00:00:00.000Z"),
        };
        // Specify the length of the object content to upload. If the actual object length is greater than the specified length, the object is truncated. Only the content of the specified length is uploaded. If the actual object length is smaller than the specified length, all content of the object is uploaded. 
        metadata.ContentLength = fs.Length;
        // Specify the caching behavior of the web page when the object is downloaded. 
        metadata.CacheControl = "No-Cache";
        // Set mykey1 to myval1. 
        metadata.UserMetadata.Add("mykey1", "myval1");
        // Set mykey2 to myval2. 
        metadata.UserMetadata.Add("mykey2", "myval2");
        var saveAsFilename = "Filetest123.txt";
        var contentDisposition = string.Format("attachment;filename*=utf-8''{0}", HttpUtils.EncodeUri(saveAsFilename, "utf-8"));
        // Specify a default object name when the required content is saved as an object. 
        metadata.ContentDisposition = contentDisposition;
        // Upload the object and configure object metadata. 
        client.PutObject(bucketName, objectName, fs, metadata);
        Console.WriteLine("Put object succeeded");
        // Query object metadata. 
        var oldMeta = client.GetObjectMetadata(bucketName, objectName);
        // Configure new object metadata. 
        var newMeta = new ObjectMetadata()
        {
            ContentType = "application/octet-stream",
            ExpirationTime = DateTime.Parse("2035-11-11T00:00:00.000Z"),
            // Specify the content encoding format of the object when the object is downloaded. 
            ContentEncoding = null,
            CacheControl = ""
        };
        // Configure user metadata. 
        newMeta.UserMetadata.Add("author", "oss");
        newMeta.UserMetadata.Add("flag", "my-flag");
        newMeta.UserMetadata.Add("mykey2", "myval2-modified-value");
        // Use the ModifyObjectMeta method to modify the object metadata. 
        client.ModifyObjectMeta(bucketName, objectName, newMeta);
    }
}
catch (Exception ex)
{
    Console.WriteLine("Put object failed, {0}", ex.Message);
}

Referências

  • Para obter o código de exemplo completo usado para configurar, modificar e obter metadados de objeto, acesse o GitHub.

  • Para obter mais informações sobre a operação de API usada para configurar metadados de objeto durante um upload simples, consulte PutObject.

  • Para obter mais informações sobre a operação de API que permite modificar metadados de objeto ao copiar um objeto, consulte CopyObject

  • Para obter mais informações sobre as operações de API usadas para consultar metadados de objeto, consulte GetObjectMeta e HeadObject.