Devido à política de mesma origem dos navegadores, solicitações entre origens podem ser rejeitadas durante a troca de dados ou o compartilhamento de recursos entre domínios diferentes. Para resolver esse problema, configure regras de compartilhamento de recursos entre origens (CORS). Nessas regras, especifique os domínios permitidos para envio de solicitações, os métodos aceitos para requisições entre origens e os cabeçalhos autorizados.
Observações
Este tópico utiliza o endpoint público da região China (Hangzhou). Caso precise acessar o OSS a partir de outros serviços do Alibaba Cloud na mesma região, utilize um endpoint interno. Para 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 via credenciais do Security Token Service (STS), consulte Inicialização (C# SDK V1).
Para configurar regras de CORS, você precisa da permissão
oss:PutBucketCors. Para consultar regras de CORS, é necessária a permissãooss:GetBucketCors. Para excluir regras de CORS, você deve ter a permissãooss:DeleteBucketCors. Para mais informações, consulte Conceder uma política personalizada.
Configurar regras de CORS
O código de exemplo a seguir mostra como definir uma regra de CORS para 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 = "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 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 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
{
var request = new SetBucketCorsRequest(bucketName);
var rule1 = new CORSRule();
// Specify the origins from which cross-origin requests are allowed.
rule1.AddAllowedOrigin("http://example.com");
// Specify the methods that can be used to send cross-origin requests, including GET, PUT, DELETE, POST, and HEAD.
rule1.AddAllowedMethod("POST");
// AllowedHeaders and ExposeHeaders do not support wildcard characters.
rule1.AddAllowedHeader("*");
// Specify the response headers for allowed access requests from applications.
rule1.AddExposeHeader("x-oss-test");
// You can configure up to 10 CORS rules for a bucket.
request.AddCORSRule(rule1);
var rule2 = new CORSRule();
// You can use only one asterisk (*) as a wildcard character for AllowedOrigins and AllowedMethods in a CORS rule. The asterisk (*) wildcard character specifies that all origins or operations are allowed.
rule2.AddAllowedOrigin("http://example.net");
rule2.AddAllowedMethod("GET");
// Specify whether the headers that are specified by Access-Control-Request-Headers in the OPTIONS preflight request are allowed.
rule2.AddExposeHeader("x-oss-test2");
// Specify the period of time in which the browser can cache the response for an OPTIONS preflight request for specific resources. Unit: seconds.
rule2.MaxAgeSeconds = 100;
request.AddCORSRule(rule2);
// Configure the CORS rules.
client.SetBucketCors(request);
Console.WriteLine("Set bucket:{0} Cors succeeded ", bucketName);
}
catch (OssException ex)
{
Console.WriteLine("Failed with error info: {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);
}
Consultar regras de CORS
Para obter o código completo de consulta de regras de CORS, acesse o GitHub.
O código de exemplo a seguir mostra como consultar as regras de CORS de 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 = "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 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 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
{
// Query the CORS rules.
var result = client.GetBucketCors(bucketName);
Console.WriteLine("Get bucket:{0} Cors succeeded ", bucketName);
foreach (var rule in result)
{
foreach (var origin in rule.AllowedOrigins)
{
Console.WriteLine("Allowed origin:{0}", origin);
}
}
}
catch (OssException ex)
{
Console.WriteLine("Failed with error info: {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);
}
Excluir regras de CORS
O código de exemplo a seguir mostra como excluir todas as regras de CORS de 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 = "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 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 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
{
// Delete the CORS rules.
client.DeleteBucketCors(bucketName);
Console.WriteLine("Delete bucket:{0} Cors succeeded ", bucketName);
}
catch (OssException ex)
{
Console.WriteLine("Failed with error info: {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 o código completo de gerenciamento de CORS, acesse o GitHub.
Para mais informações sobre a operação de API usada para configurar regras de CORS, consulte PutBucketCors.
Para mais informações sobre a operação de API usada para consultar regras de CORS, consulte GetBucketCors.
Para mais informações sobre a operação de API usada para excluir regras de CORS, consulte DeleteBucketCors.