Todos los productos
Search
Centro de documentos

Object Storage Service:Gestión de metadatos de objetos (OSS SDK for C# 1.0)

Última actualización: Sep 22, 2026

Los objetos almacenados en Object Storage Service (OSS) se componen de claves, datos y metadatos. Los metadatos describen el objeto e incluyen encabezados HTTP estándar y metadatos de usuario. Al configurar los encabezados HTTP estándar, puede crear directivas personalizadas para las solicitudes HTTP, como directivas de caché o de descarga forzada de objetos. Además, configure metadatos de usuario para identificar la finalidad o los atributos de un objeto.

Notas

  • En este tema se utiliza el endpoint público de la región China (Hangzhou). Si necesita acceder a OSS desde otros servicios de Alibaba Cloud ubicados en la misma región, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.

  • Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para conocer configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Initialization (C# SDK V1).

  • Para configurar metadatos de objetos, requiere el permiso oss:PutObject. Para consultarlos, requiere el permiso oss:GetObject. Para obtener más información, consulte Grant a custom policy.

Código de ejemplo

A continuación se muestra un ejemplo de cómo configurar, modificar y consultar metadatos de objetos:

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);
}

Referencias

  • Para consultar el código de ejemplo completo que permite configurar, modificar y obtener metadatos de objetos, visite GitHub.

  • Para obtener más información sobre la operación de API que permite configurar metadatos de objetos durante una carga simple, consulte PutObject.

  • Si desea conocer más detalles sobre la operación de API que permite modificar metadatos de objetos al copiar un objeto, consulte CopyObject

  • Para obtener más información sobre la operación de API que permite consultar metadatos de objetos, consulte GetObjectMeta y HeadObject.