.net对接阿里云CSB服务

public Response<string> Main(MonthPlanRequest request)
		{
			string apiName = "MonthPlan", postData =   request.ToJson(); 
			var result = ConnectCSB(apiName, postData);
			return InvokeResult.Fail<string>("访问成功");
		}
	/// 
		/// 请求方式post,参数为json格式
		/// 
		/// api名称
		/// 发送的参数
		/// 
		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;
		}
	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;
		}
/// 
		/// 本方法生成http请求的csb签名值。
		/// 调用csb服务时,需要在httpheader中增加以下几个头信息:
		/// _api_name: csb服务名
		/// _api_version: csb服务版本号
		/// _api_access_key: csb上的凭证ak
		/// _api_timestamp: 时间戳
		/// _api_signature: 本方法返回的签名串
		/// 
		/// csb服务名
		/// csb服务版本号
		/// 时间戳
		/// csb上的凭证ak
		/// csb上凭证的sk
		/// form表单提交的参数列表(各参数值是还未urlEncoding编码的原始业务参数值)。如果是form提交,请使用 Content-Type= application/x-www-form-urlencoded 
		/// 非form表单方式提交的请求内容,目前没有参与签名计算
		/// 签名串。
		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));
		}
		
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 + "'}]";
		}
		
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;

		}

你可能感兴趣的:(后端,C#,.net,开发语言)