Todos os produtos
Search
Central de documentação

Object Storage Service:Static website hosting (C# SDK V1)

Última atualização: Jul 03, 2026

Configure um bucket para hospedar um site estático. Após a configuração, as solicitações ao endpoint do site entregam o conteúdo diretamente do bucket. O sistema redireciona automaticamente para a página inicial padrão e para a página 404 padrão especificadas.

Observações

  • Este tópico utiliza 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, utilize um endpoint interno. Para obter mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.

  • O exemplo abaixo demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Inicialização (C# SDK V1).

  • Para definir a hospedagem de site estático, você precisa da permissão oss:PutBucketWebsite. Para recuperar a configuração de hospedagem de site estático, é necessária a permissão oss:GetBucketWebsite. Já para excluir essa configuração, utilize a permissão oss:DeleteBucketWebsite. Para mais detalhes, consulte Conceder políticas de acesso personalizadas a um usuário RAM.

Configure a hospedagem de site estático

O código a seguir mostra como configurar a hospedagem de site estático:

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

// Replace yourEndpoint with the Endpoint of the region where the bucket is located. For example, for 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 this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the bucket name.
var bucketName = "examplebucket";
// Specify the region where the bucket is located. For example, for the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";

// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();

// Use Signature V4.
conf.SignatureVersion = SignatureVersion.V4;

// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
    // Set the default homepage to index.html and the default 404 page to error.html for static website hosting.
    var request = new SetBucketWebsiteRequest(bucketName, "index.html", "error.html");
    client.SetBucketWebsite(request);
    Console.WriteLine("Set bucket:{0} Website succeeded ", bucketName);
}
catch (OssException ex)
{
    Console.WriteLine("Failed with error code: {0}; Error message: {1}. \nRequestID:{2}\tHostID:{3}",
        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
    Console.WriteLine("Failed with error message: {0}", ex.Message);
}

Visualize a configuração de hospedagem de site estático

O código a seguir mostra como visualizar a configuração de hospedagem de site estático:

using Aliyun.OSS;
using Aliyun.OSS.Common;
// Replace yourEndpoint with the Endpoint of the region where the bucket is located. For example, for 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 this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the bucket name.
var bucketName = "examplebucket";
// Specify the region where the bucket is located. For example, for the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";

// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();

// Use Signature V4.
conf.SignatureVersion = SignatureVersion.V4;

// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
    // View the static website hosting configuration.
    var result = client.GetBucketWebsite(bucketName);
    Console.WriteLine("Get bucket:{0} Website succeeded, index doc:{1}, error doc:{2}",
                      bucketName, result.IndexDocument, result.ErrorDocument);
}
catch (OssException ex)
{
    Console.WriteLine("Failed with error code: {0}; Error message: {1}. \nRequestID:{2}\tHostID:{3}",
        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
    Console.WriteLine("Failed with error message: {0}", ex.Message);
}

Exclua a configuração de hospedagem de site estático

O código a seguir mostra como excluir a configuração de hospedagem de site estático:

using Aliyun.OSS;
using Aliyun.OSS.Common;
// Replace yourEndpoint with the Endpoint of the region where the bucket is located. For example, for 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 this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the bucket name.
var bucketName = "examplebucket";
// Specify the region where the bucket is located. For example, for the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";

// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();

// Use Signature V4.
conf.SignatureVersion = SignatureVersion.V4;

// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
    // Delete the static website hosting configuration.
    client.DeleteBucketWebsite(bucketName);
    Console.WriteLine("Delete bucket:{0} Website succeeded ", bucketName);
}
catch (OssException ex)
{
    Console.WriteLine("Failed with error code: {0}; Error message: {1}. \nRequestID:{2}\tHostID:{3}", 
        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
    Console.WriteLine("Failed with error message: {0}", ex.Message);
}

Referências

  • Para acessar o código de exemplo completo sobre hospedagem de site estático, consulte o exemplo no GitHub.

  • Para obter mais informações sobre a operação de API destinada a configurar a hospedagem de site estático, consulte PutBucketWebsite.

  • Para detalhes sobre a operação de API usada para visualizar a configuração de hospedagem de site estático, consulte GetBucketWebsite.

  • Caso precise de informações sobre a operação de API para excluir a configuração de hospedagem de site estático, consulte DeleteBucketWebsite.