Cross-origin resource sharing (CORS) is a standard cross-origin solution provided by HTML5 to allow web application servers to control cross-origin access. This way, the security of data transmission across origins is ensured.

Configure CORS rules

The following code provides an example on how to configure CORS rules for a specific bucket:

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

// Set endpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to access OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
var accessKeyId = "yourAccessKeyId";
var accessKeySecret = "yourAccessKeySecret";
// Specify the name of the bucket. Example: examplebucket. 
var bucketName = "examplebucket";

// Create an OSSClient instance. 
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
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 HTTP methods that cross-origin requests are allowed to use, including PUT, POST, GET, DELETE, 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 the bucket. 
    request.AddCORSRule(rule1);
    var rule2 = new CORSRule();
    // You can use only one asterisk (*) as the 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 to 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);
}

Query CORS rules

The following code provides an example on how to query CORS rules that are configured for a specific bucket:

using Aliyun.OSS;
using Aliyun.OSS.Common;
// Set endpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to access OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
var accessKeyId = "yourAccessKeyId";
var accessKeySecret = "yourAccessKeySecret";
// Specify the name of the bucket. Example: examplebucket. 
var bucketName = "examplebucket";

// Create an OSSClient instance. 
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
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);
}

Delete CORS rules

The following code provides an example on how to delete the CORS rules that are configured for a specific bucket:

using Aliyun.OSS;
using Aliyun.OSS.Common;
// Set endpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to access OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
var accessKeyId = "yourAccessKeyId";
var accessKeySecret = "yourAccessKeySecret";
// Specify the name of the bucket. Example: examplebucket. 
var bucketName = "examplebucket";

// Create an OSSClient instance. 
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
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);
}

References

  • For more information about the complete sample code of CORS, visit GitHub.
  • For more information about the API operation that you can call to configure CORS rules, see PutBucketCors.
  • For more information about the API operation that you can call to query CORS rules, see GetBucketCors.
  • For more information about the API operation that you can call to delete CORS rules, see DeleteBucketCors.