对象存储OSS使用C#语言实现签名Header上传的示例

概述

对象存储OSS SDK提供了集成签名、上传和下载的SDK,但实际使用中,有时需要使用API的方式实现在签名的情况下进行上传和下载。本文以PutObject接口为例,为您提供C#语言实现的示例。

说明

建议优先使用OSS提供SDK,本文提供的只是签名实现上传示例,实际使用中需要结合业务进行代码改动。

详细信息

C#使用PutObject接口实现示例代码如下。

说明

以下示例在Visual Studio 2017工具和NET Framework4.0程序包中实现。

using System;
using System.Security.Cryptography;
using System.Text;
using System.Net;
using System.IO;
using System.Reflection;


namespace Aliyun.OSS.Samples
{
    class Program
    {



        //您的AccessKey
        public static string AccessKey = "xx";
        //您的AccessKeySecret
        public static string AccessKeySecret = "xx";
        //Bucket所在的endpoint
        public static string Endpoint = "oss-cn-hangzhou.aliyuncs.com";
        public static string BucketName = "xx";
        public static string objectName = "mytest/1.txt";
        public static string HmacSha1Sign(string secret, string strOrgData)
        {
            var hmacsha1 = new HMACSHA1(Encoding.UTF8.GetBytes(secret));
            var dataBuffer = Encoding.UTF8.GetBytes(strOrgData);
            var hashBytes = hmacsha1.ComputeHash(dataBuffer);
            return Convert.ToBase64String(hashBytes);
        }


        public static string HttpRequest(string url, string data, string sign, string contentType, string time1)
        {


            byte[] datas = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "PUT";
            request.Timeout = 150000;
            request.Headers.Add("Authorization", "OSS " + AccessKey + ":" + sign);
            CallPrivateMethod(request, "SetSpecialHeaders", "Date", time1);
            request.ContentType = contentType;
            Stream requestStream = null;
            string responseStr = null;
            try
            {
                if (datas != null)
                {
                    request.ContentLength = datas.Length;
                    requestStream = request.GetRequestStream();
                    requestStream.Write(datas, 0, datas.Length);
                    requestStream.Close();
                }
                else
                {
                    request.ContentLength = 0;
                }
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                responseStr = response.Headers.GetValues("x-oss-request-id")[0];
                //responseStr = sr.ReadToEnd();
            }
            catch (Exception)
            {
                Console.WriteLine("error");
            }
            finally
            {
                request = null;
                requestStream = null;
            }
            return responseStr;
        }


        public static string ToGMTString()
        {
            return DateTime.Now.ToUniversalTime().ToString("r");
        }
        public static void CallPrivateMethod(object instance, string name, params object[] param)
        {
            BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic;
            Type type = instance.GetType();
            MethodInfo method = type.GetMethod(name, flag);
            method.Invoke(instance, param);
        }


        static void Main(string[] args)
        {


            string varb = "PUT";
            string content_type = "application/json";
            string timeGmt = ToGMTString();
            string str = varb + "\n\n" + content_type + "\n" + timeGmt + "\n/" + BucketName + "/" + objectName;
            string signature = HmacSha1Sign(AccessKeySecret, str);
            string url = "http://" + BucketName + "." + Endpoint + "/" + objectName;
            string data = "{ \"key\":\"this is a oss's test\"}";
            string result = HttpRequest(url, data, signature, content_type, timeGmt);
            Console.WriteLine("requestId:  " + result);




        }
    }
}

相关文档

若您需要使用对象存储OSS提供SDK,请参见OSS在Header中包含签名

适用于

  • 对象存储OSS