.net对接阿里云CSB服务

csharp 复制代码
public Response<string> Main(MonthPlanRequest request)
		{
			string apiName = "MonthPlan", postData =   request.ToJson(); 
			var result = ConnectCSB(apiName, postData);
			return InvokeResult.Fail<string>("访问成功");
		}
csharp 复制代码
	/// <summary>
		/// 请求方式post,参数为json格式
		/// </summary>
		/// <param name="apiName">api名称</param>
		/// <param name="postData">发送的参数</param>
		/// <returns></returns>
		public static string ConnectCSB(string apiName, string postData)
		{
			var resultStr = "";
			try
			{
				string ACCESS_KEY = System.Configuration.ConfigurationManager.AppSettings["ACCESS_KEY"].ToString();
				string SECRET_KEY = System.Configuration.ConfigurationManager.AppSettings["SECRET_KEY"].ToString();
				string CSBURL = System.Configuration.ConfigurationManager.AppSettings["CSBURL"].ToString();
				//签名时间戳
				long timeStamp = ToUnixTimeMilliseconds(DateTime.Now);

				//form表单提交的签名串生成示例
				string signature = sign(apiName, "1.0.0", timeStamp, ACCESS_KEY, SECRET_KEY, null, postData);

				Dictionary<string, string> headerDic = new Dictionary<string, string>();
				headerDic.Add("_api_access_key", ACCESS_KEY);//访问密钥
				headerDic.Add("_api_timestamp", timeStamp.ToString());//签名时间戳
				headerDic.Add("_api_name", apiName);  //需要调用的api名称
				headerDic.Add("_api_signature", signature);//签名
				headerDic.Add("_api_version", "1.0.0");//版本																	
				resultStr = GetResult(CSBURL, "application/json", "application/json;charset=utf-8", "POST", postData, headerDic);
			}
			catch (Exception e)
			{
				ErpErrLog(e.Message, apiName);
				return "[{'IsSuccess': 'false','Msg':'" + e.Message + "'}]";
			}
			return resultStr;
		}
csharp 复制代码
	public static long ToUnixTimeMilliseconds(DateTime nowTime)
		{

			DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));

			// DateTime nowTime = DateTime.Now;

			long unixTime = (long)Math.Round((nowTime - startTime).TotalMilliseconds, MidpointRounding.AwayFromZero);
			return unixTime;
		}
csharp 复制代码
/// <summary>
		/// 本方法生成http请求的csb签名值。
		/// 调用csb服务时,需要在httpheader中增加以下几个头信息:
		/// _api_name: csb服务名
		/// _api_version: csb服务版本号
		/// _api_access_key: csb上的凭证ak
		/// _api_timestamp: 时间戳
		/// _api_signature: 本方法返回的签名串
		/// </summary>
		/// <param name="apiName">csb服务名</param>
		/// <param name="apiVersion">csb服务版本号</param>
		/// <param name="timeStamp">时间戳</param>
		/// <param name="accessKey">csb上的凭证ak</param>
		/// <param name="secretKey">csb上凭证的sk</param>
		/// <param name="formParamDict">form表单提交的参数列表(各参数值是还未urlEncoding编码的原始业务参数值)。如果是form提交,请使用 Content-Type= application/x-www-form-urlencoded </param>
		/// <param name="body">非form表单方式提交的请求内容,目前没有参与签名计算</param>
		/// <returns>签名串。</returns>
		public static string sign(string apiName, string apiVersion, long timeStamp, string accessKey, string secretKey, Dictionary<string, object[]> formParamDict, object body)
		{
			Dictionary<string, object[]> newDict = new Dictionary<string, object[]>();
			if (formParamDict != null)
			{
				foreach (KeyValuePair<string, object[]> pair in formParamDict)
				{
					newDict.Add(pair.Key, pair.Value.Select(v => { return HttpUtility.UrlEncode(v.ToString()); }
					).ToArray());
				}
			}

			//设置csb要求的头参数
			newDict.Add("_api_name", new String[] { apiName });
			newDict.Add("_api_version", new String[] { apiVersion });
			newDict.Add("_api_access_key", new String[] { accessKey });
			newDict.Add("_api_timestamp", new object[] { timeStamp });

			//对所有参数进行排序
			var sortedDict = getSortByASCII(newDict);
			StringBuilder builder = new StringBuilder();
			foreach (KeyValuePair<string, object[]> pair in sortedDict)
			{
				foreach (object obj in pair.Value)
				{
					builder.Append(string.Format("{0}={1}&", pair.Key, obj));
				}
			}
			string str = builder.ToString();
			if (str.EndsWith("&"))
			{
				str = str.Substring(0, str.Length - 1); //去掉最后一个多余的 & 符号
			}
			System.Security.Cryptography.HMACSHA1 hmacsha = new System.Security.Cryptography.HMACSHA1
			{
				Key = Encoding.UTF8.GetBytes(secretKey)
			};
			byte[] bytes = Encoding.UTF8.GetBytes(str);
			return Convert.ToBase64String(hmacsha.ComputeHash(bytes));
		}
		
csharp 复制代码
public static string GetResult(string url, string accept, string contentType, string requestType, string parms, Dictionary<string, string> headerDic = null)
		{

			var result = string.Empty;

			try
			{
				Stopwatch stopWatch = new Stopwatch();
				stopWatch.Start();
				var myRequest = (HttpWebRequest)WebRequest.Create(url);
				myRequest.Timeout = 300000;//100秒超时时间较短,需要调整成为300秒
				if (!string.IsNullOrEmpty(accept))
				{
					myRequest.Accept = accept;
				}
				if (!string.IsNullOrEmpty(contentType))
				{
					myRequest.ContentType = contentType;
				}
				//   myRequest.Headers.Add(new HttpRequestHeader(),"123");
				myRequest.Method = requestType;
				if (myRequest.Method == "POST")
				{
					var reqStream = myRequest.GetRequestStream();
					var encoding = Encoding.GetEncoding("utf-8");
					var inData = encoding.GetBytes(parms);
					reqStream.Write(inData, 0, inData.Length);
					reqStream.Close();
				}

				if (headerDic != null)
				{
					foreach (var h in headerDic)
					{
						myRequest.Headers.Add(h.Key, h.Value);
					}
				}
				//发送post请求到服务器并读取服务器返回信息    
				var res = (HttpWebResponse)myRequest.GetResponse();

				if (res.StatusCode != HttpStatusCode.OK) return result;

				var receiveStream = res.GetResponseStream();
				var encode = Encoding.GetEncoding("utf-8");
				if (receiveStream != null)
				{
					var readStream = new StreamReader(receiveStream, encode);
					var oResponseMessage = readStream.ReadToEnd();
					res.Close();
					readStream.Close();
					result = oResponseMessage;
					ErpResult re = JsonConvert.DeserializeObject(result, typeof(ErpResult)) as ErpResult;
					if (re.code.Equals("000000"))
					{ 
							return "[{'IsSuccess': 'true','Msg':'" + re.message + "'}]";
					}
					else
							return "[{'IsSuccess': 'false','Msg':'" + re.message + "'}]";

				}
				stopWatch.Stop();

			}
			catch (Exception e)
			{
				ErpErrLog(e.Message, headerDic["_api_name"].ToString());
				if (e is WebException && ((WebException)e).Status == WebExceptionStatus.ProtocolError)
				{
					WebResponse errResp = ((WebException)e).Response;
					using (Stream respStream = errResp.GetResponseStream())
					{
						var readStream = new StreamReader(respStream, Encoding.GetEncoding("utf-8"));
						var strError = readStream.ReadToEnd();
						Console.Out.WriteLine(strError);
						// read the error response
					}
				}
				return "[{'IsSuccess': 'false','Msg':'"+e.Message+"'}]";
			}
			return "[{'IsSuccess': 'true','Msg':'" + result + "'}]";
		}
		
csharp 复制代码
public static Dictionary<string, object[]> getSortByASCII(Dictionary<string, object[]> dict)
		{

			var sortList = dict.ToList();
			
			//经过测试以下三种是正确的,会按照ASCII码排序
			sortList.Sort((x, y) =>
			{

				return string.CompareOrdinal(x.Key, y.Key);
			});
			sortList.Sort((x, y) =>
			{

				var r = string.Compare(x.Key, y.Key, StringComparison.Ordinal);
				return r;
			});

			Dictionary<string, object[]> sortDict = new Dictionary<string, object[]>();
			var keys = dict.Keys.ToArray();
			Array.Sort(keys, string.CompareOrdinal); //an
			foreach (var key in keys)
			{
				sortDict.Add(key, dict[key]);
			}
			return sortDict;

		}
相关推荐
Chrikk23 分钟前
Go-性能调优实战案例
开发语言·后端·golang
幼儿园老大*26 分钟前
Go的环境搭建以及GoLand安装教程
开发语言·经验分享·后端·golang·go
canyuemanyue26 分钟前
go语言连续监控事件并回调处理
开发语言·后端·golang
杜杜的man29 分钟前
【go从零单排】go语言中的指针
开发语言·后端·golang
萧鼎2 小时前
Python并发编程库:Asyncio的异步编程实战
开发语言·数据库·python·异步
学地理的小胖砸2 小时前
【一些关于Python的信息和帮助】
开发语言·python
疯一样的码农2 小时前
Python 继承、多态、封装、抽象
开发语言·python
^velpro^2 小时前
数据库连接池的创建
java·开发语言·数据库
秋の花2 小时前
【JAVA基础】Java集合基础
java·开发语言·windows
小松学前端2 小时前
第六章 7.0 LinkList
java·开发语言·网络