OptionObjectRequest.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using COSXML.Common;
  5. using COSXML.CosException;
  6. namespace COSXML.Model.Object
  7. {
  8. /// <summary>
  9. /// 实现 Object 跨域访问配置的预请求
  10. /// <see href="https://cloud.tencent.com/document/product/436/8288"/>
  11. /// </summary>
  12. public sealed class OptionObjectRequest : ObjectRequest
  13. {
  14. /// <summary>
  15. /// 模拟跨域访问的请求来源域名
  16. /// </summary>
  17. private string origin;
  18. /// <summary>
  19. /// 模拟跨域访问的请求 HTTP 方法
  20. /// </summary>
  21. private string accessControlMethod;
  22. public OptionObjectRequest(string bucket, string key, string origin, string accessControlMethod)
  23. : base(bucket, key)
  24. {
  25. this.method = CosRequestMethod.OPTIONS;
  26. this.origin = origin;
  27. if (accessControlMethod != null)
  28. {
  29. this.accessControlMethod = accessControlMethod.ToUpper();
  30. }
  31. }
  32. /// <summary>
  33. /// 模拟跨域访问的请求头部
  34. /// </summary>
  35. /// <param name="accessControlHeaders"></param>
  36. public void SetAccessControlHeaders(List<string> accessControlHeaders)
  37. {
  38. if (accessControlHeaders != null)
  39. {
  40. StringBuilder headers = new StringBuilder();
  41. foreach (string accessControlHeader in accessControlHeaders)
  42. {
  43. if (accessControlHeader != null)
  44. {
  45. headers.Append(accessControlHeader).Append(",");
  46. }
  47. }
  48. string result = headers.ToString();
  49. if (result.EndsWith(","))
  50. {
  51. result = result.Substring(0, result.Length - 1);
  52. SetRequestHeader(CosRequestHeaderKey.ACCESS_CONTROL_REQUEST_HEADERS, result);
  53. }
  54. }
  55. }
  56. public override void CheckParameters()
  57. {
  58. if (origin == null)
  59. {
  60. throw new CosClientException((int)CosClientError.InvalidArgument, "origin = null");
  61. }
  62. if (accessControlMethod == null)
  63. {
  64. throw new CosClientException((int)CosClientError.InvalidArgument, "accessControlMethod = null");
  65. }
  66. base.CheckParameters();
  67. }
  68. protected override void InteranlUpdateHeaders()
  69. {
  70. try
  71. {
  72. this.headers.Add(CosRequestHeaderKey.ORIGIN, origin);
  73. }
  74. catch (ArgumentException)
  75. {
  76. this.headers[CosRequestHeaderKey.ORIGIN] = origin;
  77. }
  78. try
  79. {
  80. this.headers.Add(CosRequestHeaderKey.ACCESS_CONTROL_REQUEST_METHOD, accessControlMethod);
  81. }
  82. catch (ArgumentException)
  83. {
  84. this.headers[CosRequestHeaderKey.ACCESS_CONTROL_REQUEST_METHOD] = accessControlMethod;
  85. }
  86. }
  87. }
  88. }