腾讯云 对象存储(COS) 踩坑

按官方SDK指引编译运行后报错

CosClientException:
   COSXML.CosException.CosClientException:
      Error: NameResolutionFailure --->
         System.Net.WebException: Error: NameResolutionFailure

调试后发现 cosXml 中的 Appid 为 null

CosXmlConfig config = new CosXmlConfig.Builder()
             .SetAppid("appid") //←←← 在config中追加Appid
             .SetRegion("COS_REGION")
             .Build();

修改并添加Appid后上传成功

200 OK
Content-Length: 0
Connection: keep-alive
Date: Sat, 06 May 2023 00:43:47 GMT
ETag: "644a534b4052646cd8e2fg2hijklm97n"
Server: tencent-cos
x-cos-hash-crc64ecma: 9876543210987654321
x-cos-request-id: AbCdEFGhIjKlMnOpQrStUVWxYzabCDEfGHIjKlMnOPQ=
x-cos-storage-class: STANDARD

以下代码摘自官方 示例代码二: 上传二进制数据

戳这里👉 查看SDK原文
using COSXML.Model.Object;
using COSXML.Auth;
using COSXML.Transfer;
using System;
using COSXML;

namespace COSSnippet
{
    public class TransferUploadObjectModel {

      private CosXml cosXml;

      TransferUploadObjectModel() {
        CosXmlConfig config = new CosXmlConfig.Builder()
                     .SetRegion("COS_REGION")
                     .Build();

        string secretId = "SECRET_ID";
        string secretKey = "SECRET_KEY";
        long durationSecond = 600;
        QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCredentialProvider(secretId, secretKey, durationSecond);

        this.cosXml = new CosXmlServer(config, qCloudCredentialProvider);
      }

      /// 上传二进制数据
      public void TransferUploadBytes()
      {
        try
        {
          string bucket = "examplebucket-1250000000";
          string cosPath = "exampleObject";
          byte[] data = new byte[1024];
          PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, cosPath, data);
          // 发起上传
          PutObjectResult result = cosXml.PutObject(putObjectRequest);
          Console.WriteLine(result.GetResultInfo());
        }
        catch (COSXML.CosException.CosClientException clientEx)
        { //请求失败
          Console.WriteLine("CosClientException: " + clientEx);
        }
        catch (COSXML.CosException.CosServerException serverEx)
        { //请求失败
          Console.WriteLine("CosServerException: " + serverEx.GetInfo());
        }
      }

      static void Main(string[] args)
      {
        TransferUploadObjectModel m = new TransferUploadObjectModel();

        /// 高级接口上传二进制数据
        m.TransferUploadBytes();
      }
    }
}

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注