CORS

Last Updated: Jun 06, 2017

Cross-origin Resource Sharing (CORS) allows Web applications to access resources in other domains. OSS provides an interface for developers to conveniently control cross-origin access permissions.

Set CORS rules

The setBucketCors method can be used to configure a CORS rule for a specified bucket. If a rule already exists, it will be overwritten by the new one.

Parameters for specific rules are generally set through the CORSRule class. The code is as follows:

  1. using Aliyun.OSS;
  2. // Initialize an OSSClient
  3. var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
  4. var req = new SetBucketCorsRequest(bucketName);
  5. var r1 = new CORSRule();
  6. //Specify the allowed source of cross-origin requests
  7. r1.AddAllowedOrigin("http://www.a.com");
  8. //Specify the allowed cross-origin request methods (GET/PUT/DELETE/POST/HEAD)
  9. r1.AddAllowedMethod("POST");
  10. //Control whether the headers specified by Access-Control-Request-Headers in the OPTIONS' prefetch command are allowed.
  11. r1.AddAllowedHeader("*");
  12. //Specify the response headers users are allowed to access from the application
  13. r1.AddExposeHeader("x-oss-test");
  14. req.AddCORSRule(r1);
  15. client.SetBucketCors(req);

Complete code can be found at: GitHub

Note:

  • Each bucket allows a maximum of 10 rules.
  • The AllowedOrigins and AllowedMethods each supports up to one “*“ wildcard. “*“ indicates that all origin sources or operations are allowed.
  • AllowedHeaders and ExposeHeaders do not support wildcards.

Get CORS rules

The GetBucketCors method can be used to access the CORS rules of a bucket. The code is as follows:

  1. using Aliyun.OSS;
  2. // Initialize an OSSClient
  3. var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
  4. var rules = client.GetBucketCors(bucketName);
  5. foreach (var rule in rules)
  6. {
  7. Console.WriteLine("AllowedOrigins:{0}", rule.AllowedOrigins);
  8. Console.WriteLine("AllowedMethods:{0}", rule.AllowedMethods);
  9. Console.WriteLine("AllowedHeaders:{0}", rule.AllowedHeaders);
  10. Console.WriteLine("ExposeHeaders:{0}", rule.ExposeHeaders);
  11. Console.WriteLine("MaxAgeSeconds:{0}", rule.MaxAgeSeconds);
  12. }

Note: Complete code can be found at: GitHub

Delete a CORS rule

The following code disables CORS for a specified bucket and clears all its CORS rules:

  1. using Aliyun.OSS;
  2. // Initialize an OSSClient
  3. var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
  4. // Clear the CORS rules of a bucket
  5. client.DeleteBucketCors(bucketName);

Note: Complete code can be found at: GitHub

Thank you! We've received your feedback.