C#后台发起http请求_c# 后台web请求-程序员宅基地

技术标签: C#  c#  http  开发语言  

C#后台发起请求

HttpWebRequest 方式

发起POST请求代码

  /// <summary>
        /// POST请求与获取结果  
        /// </summary>
        /// <param name="Url">请求地址</param>
        /// <param name="parames">请求参数</param>
        /// <returns>返回请求结果</returns>
        ///sign和timestamp和mchid参数可以根据自己的项目需要选择要或者不要
        public static string HttpPost(string Url, Dictionary<String, String> parames, string sign=null,string timestamp=null, string mchid=null)
        {
    
            String postDataStr = buildParamStr(parames);
          
            try
            {
    
                //https免证书发起请求
              ServicePointManager.ServerCertificateValidationCallback = Globals.CheckValidationResult;
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(Url);
                httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                httpWebRequest.Method = "POST";//请求类型可以换成Get就是发起get请求了
                httpWebRequest.Timeout = 60000;
                if (!string.IsNullOrWhiteSpace(sign)) httpWebRequest.Headers.Add("sign", sign);//向请求头里添加内容【键值对】
                if (!string.IsNullOrWhiteSpace(timestamp)) httpWebRequest.Headers.Add("timestamp", timestamp);
                if (!string.IsNullOrWhiteSpace(mchid)) httpWebRequest.Headers.Add("mchid", mchid);
                if (parames.Count > 0)
                {
    
                byte[] btBodys = Encoding.UTF8.GetBytes(postDataStr);
                httpWebRequest.ContentLength = btBodys.Length;
                httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);
                }
                HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
                string responseContent = streamReader.ReadToEnd();
                httpWebResponse.Close();
                streamReader.Close();
                httpWebRequest.Abort();
                httpWebResponse.Close();
                return responseContent;
            }
            catch (Exception ex)
            {
    
                LogHelper.WriteBarcodesLog("HttpPost:" + Url + "||postDataStr:" + postDataStr + "\r\n" + ex.Message, "HttpHelper_Error");
                return ex.Message;
            }
        }

//这种方式是将数据存入body里进行请求
public static string HttpPost(string url, string postData)
		{
    
			string result = string.Empty;
			try
			{
    
				Uri requestUri = new Uri(url);
				HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
				Encoding uTF = Encoding.UTF8;
				byte[] bytes = uTF.GetBytes(postData);
				httpWebRequest.Method = "POST";
				httpWebRequest.ContentType = "application/x-www-form-urlencoded";
				httpWebRequest.ContentLength = bytes.Length;
				using (Stream stream = httpWebRequest.GetRequestStream())
				{
    
					stream.Write(bytes, 0, bytes.Length);
				}
				using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
				{
    
					using (Stream stream2 = httpWebResponse.GetResponseStream())
					{
    
						Encoding uTF2 = Encoding.UTF8;
						Stream stream3 = stream2;
						if (httpWebResponse.ContentEncoding.ToLower() == "gzip")
						{
    
							stream3 = new GZipStream(stream2, CompressionMode.Decompress);
						}
						else if (httpWebResponse.ContentEncoding.ToLower() == "deflate")
						{
    
							stream3 = new DeflateStream(stream2, CompressionMode.Decompress);
						}
						using (StreamReader streamReader = new StreamReader(stream3, uTF2))
						{
    
							result = streamReader.ReadToEnd();
						}
					}
				}
			}
			catch (Exception ex)
			{
    
				result = $"获取信息错误:{
      ex.Message}";
			}
			return result;
		}

发起Get请求代码

public static string HttpGet(string Url, Dictionary<String, object> parames, string cookie = null, bool isencode = false)
        {
    
            String postDataStr = buildParamStr(parames);
            if (isencode)
            {
    
                //postDataStr = System.Web.HttpUtility.UrlEncode(postDataStr);
            }
            string serviceAddress = Url + "?" + postDataStr;
            try
            {
    
                HttpWebRequest request =
               (HttpWebRequest)WebRequest.Create(serviceAddress);
                request.Method = "GET";//GET请求的方式
                request.ContentType = "application/x-www-form-urlencoded";//编码格式以及请求类型,这行代码很关键,不设置ContentType将可能导致后台参数获取不到值
                request.Credentials = CredentialCache.DefaultCredentials;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream,
                 Encoding.UTF8);
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                return retString;//返回链接字符串
            }
            catch (Exception ex)
            {
    
                LogHelper.WriteBarcodesLog("HttpGet:" + Url + "||postDataStr:" + postDataStr + "\r\n" + ex.Message, "HttpHelper_Error");
                return ex.Message;
            }
        }

其他辅助代码

public static class Globals
	{
    
		public static readonly string HIPOSTAKECODEPREFIX = "YSC";
 /// <summary>
        /// 转换请求参数,拼接请求串
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        static String buildParamStr(Dictionary<string, object> param)
        {
    
            String paramStr = String.Empty;
            if (param != null)
            {
    
                foreach (var key in param.Keys.ToList())
                {
    
                    if (param.Keys.ToList().IndexOf(key) == 0)
                    {
    
                        paramStr += (key + "=" + param[key]);
                    }
                    else
                    {
    
                        paramStr += ("&" + key + "=" + param[key]);
                    }
                }
            }
            return paramStr;
        }
		public static string IPAddress
		{
    
			get
			{
    
				Regex regex = new Regex("^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$");
				IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
				string sign = hostEntry.AddressList[0].ToNullString();
				Globals.AppendLog("IPHostEntry", sign, "", "IPAddress");
				if (HttpContext.Current == null)
				{
    
					IPHostEntry hostEntry2 = Dns.GetHostEntry(Dns.GetHostName());
					sign = hostEntry2.AddressList[0].ToNullString();
				}
				else
				{
    
					sign = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
					if (sign != null && sign != string.Empty)
					{
    
						if (sign.IndexOf(".") == -1)
						{
    
							sign = null;
						}
						else if (sign.IndexOf(",") != -1)
						{
    
							sign = sign.Replace(" ", "").Replace("'", "");
							string[] array = sign.Split(",;".ToCharArray());
							for (int i = 0; i < array.Length; i++)
							{
    
								if (regex.IsMatch(array[i]) && array[i].Substring(0, 3) != "10." && array[i].Substring(0, 7) != "192.168" && array[i].Substring(0, 7) != "172.16.")
								{
    
									return array[i];
								}
							}
						}
						else
						{
    
							if (regex.IsMatch(sign))
							{
    
								return sign;
							}
							sign = null;
						}
					}
					string text = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != string.Empty) ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
					if (sign == null || sign == string.Empty)
					{
    
						sign = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
					}
					if (sign == null || sign == string.Empty)
					{
    
						sign = HttpContext.Current.Request.UserHostAddress;
					}
				}
				return sign;
			}
		}

		public static string DomainName
		{
    
			get
			{
    
				if (HttpContext.Current == null)
				{
    
					return string.Empty;
				}
				string text = HttpContext.Current.Request.Url.ToString();
				text = text.Replace("http://", "").Replace("https://", "");
				return (text.Split(':').Length <= 1) ? text.Split('/')[0] : text.Split(':')[0];
			}
		}

		public static bool IsTestDomain
		{
    
			get
			{
    
				//if (!string.IsNullOrEmpty(Globals.DomainName))
				//{
    
				//	if (Globals.DomainName.EndsWith("xm.huz.cn") || Globals.DomainName.StartsWith("localhost") || Globals.DomainName.StartsWith("127.0.0.1") || Globals.DomainName.Contains("ysctest.huz.cn") || Globals.DomainName.Contains("yscssl.huz.cn"))
				//	{
    
				//		return true;
				//	}
				//	return false;
				//}
				return true;
			}
		}

		public static bool IsIpAddress(string ip)
		{
    
			Regex regex = new Regex("^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$");
			return regex.IsMatch(ip);
		}

		public static string GetIPAddress(HttpContext context)
		{
    
			Regex regex = new Regex("^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$");
			string text;
			if (context == null)
			{
    
				IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
				text = hostEntry.AddressList[0].ToNullString();
			}
			else
			{
    
				text = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
				if (text != null && text != string.Empty)
				{
    
					if (text.IndexOf(".") == -1)
					{
    
						text = null;
					}
					else if (text.IndexOf(",") != -1)
					{
    
						text = text.Replace(" ", "").Replace("'", "");
						string[] array = text.Split(",;".ToCharArray());
						for (int i = 0; i < array.Length; i++)
						{
    
							if (regex.IsMatch(array[i]) && array[i].Substring(0, 3) != "10." && array[i].Substring(0, 7) != "192.168" && array[i].Substring(0, 7) != "172.16.")
							{
    
								return array[i];
							}
						}
					}
					else
					{
    
						if (regex.IsMatch(text))
						{
    
							return text;
						}
						text = null;
					}
				}
				if (text == null || text == string.Empty)
				{
    
					text = context.Request.ServerVariables["REMOTE_ADDR"];
				}
				if (text == null || text == string.Empty)
				{
    
					text = context.Request.UserHostAddress;
				}
			}
			return text;
		}

		public static string GetSafeSortField(string allowFields, string field, string defaultField)
		{
    
			string result = defaultField;
			string[] array = allowFields.Split(',');
			string[] array2 = array;
			foreach (string text in array2)
			{
    
				if (text.ToLower() == field.ToLower())
				{
    
					result = field;
					break;
				}
			}
			return result;
		}

		public static string GetSafeSortOrder(string sortOrder, string defaultSortOrder = "Desc")
		{
    
			string result = defaultSortOrder;
			if (!string.IsNullOrEmpty(sortOrder))
			{
    
				if (sortOrder.ToUpper() != "DESC" && sortOrder.ToUpper() != "ASC")
				{
    
					result = "Desc";
				}
				else
				{
    
					if (sortOrder.ToUpper() == "DESC")
					{
    
						result = "Desc";
					}
					if (sortOrder.ToUpper() == "ASC")
					{
    
						result = "Asc";
					}
				}
			}
			return result;
		}

		public static string GetSafeIDList(string IdList, char split = '_', bool isDistinct = true)
		{
    
			string text = "";
			if (string.IsNullOrEmpty(IdList))
			{
    
				return "";
			}
			string[] array = IdList.Split(split);
			if (isDistinct)
			{
    
				array = array.Distinct().ToArray();
			}
			long num = 0L;
			string[] array2 = array;
			foreach (string s in array2)
			{
    
				long.TryParse(s, out num);
				if (num >= 0)
				{
    
					text = text + ((text == "") ? "" : split.ToString()) + num.ToString();
				}
			}
			return text;
		}

		public static void WriteLog(string fileName, string txt)
		{
    
			string path = Globals.GetphysicsPath(fileName);
			Globals.CreatePath(path);
			try
			{
    
				using (StreamWriter streamWriter = File.AppendText(path))
				{
    
					streamWriter.WriteLine(txt);
					streamWriter.WriteLine("");
					streamWriter.Flush();
					streamWriter.Close();
				}
			}
			catch
			{
    
			}
		}

		public static string GetStoragePath()
		{
    
			return "/Storage/master";
		}

		public static string PhysicalPath(string path)
		{
    
			if (path == null)
			{
    
				return string.Empty;
			}
			string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
			char directorySeparatorChar = Path.DirectorySeparatorChar;
			string text = directorySeparatorChar.ToString();
			baseDirectory = baseDirectory.Replace("/", text);
			string text2 = "/";
			if (text2 != null)
			{
    
				text2 = text2.Replace("/", text);
				baseDirectory = ((text2.Length <= 0 || !text2.StartsWith(text) || !baseDirectory.EndsWith(text)) ? (baseDirectory + text2) : (baseDirectory + text2.Substring(1)));
			}
			string str = baseDirectory.TrimEnd(Path.DirectorySeparatorChar);
			directorySeparatorChar = Path.DirectorySeparatorChar;
			return str + directorySeparatorChar.ToString() + path.TrimStart(Path.DirectorySeparatorChar);
		}

		public static string MapPath(string path)
		{
    
			if (string.IsNullOrEmpty(path))
			{
    
				return string.Empty;
			}
			HttpContext current = HttpContext.Current;
			if (current != null)
			{
    
				return current.Request.MapPath(path);
			}
			return Globals.PhysicalPath(path.Replace("/", Path.DirectorySeparatorChar.ToString()).Replace("~", ""));
		}

		public static void RedirectToSSL(HttpContext context)
		{
    
			if (context != null && !context.Request.IsSecureConnection)
			{
    
				Uri url = context.Request.Url;
				context.Response.Redirect("https://" + url.ToString().Substring(7));
			}
		}

		public static bool IsUrlAbsolute(string url)
		{
    
			if (url == null)
			{
    
				return false;
			}
			string[] array = new string[12]
			{
    
				"about:",
				"file:///",
				"ftp://",
				"gopher://",
				"http://",
				"https://",
				"javascript:",
				"mailto:",
				"news:",
				"res://",
				"telnet://",
				"view-source:"
			};
			string[] array2 = array;
			foreach (string value in array2)
			{
    
				if (url.StartsWith(value))
				{
    
					return true;
				}
			}
			return false;
		}

		public static string GetImageServerUrl()
		{
    
			return "";// HiConfiguration.GetConfig().ImageServerUrl.ToLower();
		}

		public static string GetImageServerUrl(string flag, string imageUrl)
		{
    
			if (string.IsNullOrEmpty(imageUrl))
			{
    
				return string.Empty;
			}
			if (!imageUrl.Contains(flag) && !imageUrl.Contains("http://") && !imageUrl.Contains("https://"))
			{
    
				return Globals.FullPath(Globals.GetImageServerUrl() + imageUrl);
			}
			return imageUrl;
		}

		public static void EntityCoding(object entity, bool encode)
		{
    
			if (entity != null)
			{
    
				Type type = entity.GetType();
				PropertyInfo[] properties = type.GetProperties();
				PropertyInfo[] array = properties;
				int num = 0;
				while (true)
				{
    
					if (num < array.Length)
					{
    
						PropertyInfo propertyInfo = array[num];
						if (propertyInfo.GetCustomAttributes(typeof(HtmlCodingAttribute), true).Length != 0)
						{
    
							if (!propertyInfo.CanWrite || !propertyInfo.CanRead)
							{
    
								throw new Exception("使用HtmlEncodeAttribute修饰的属性必须是可读可写的");
							}
							if (propertyInfo.PropertyType.Equals(typeof(string)))
							{
    
								string text = propertyInfo.GetValue(entity, null) as string;
								if (!string.IsNullOrEmpty(text))
								{
    
									if (encode)
									{
    
										propertyInfo.SetValue(entity, Globals.HtmlEncode(text), null);
									}
									else
									{
    
										propertyInfo.SetValue(entity, Globals.HtmlDecode(text), null);
									}
								}
								goto IL_00f1;
							}
							break;
						}
						goto IL_00f1;
					}
					return;
					IL_00f1:
					num++;
				}
				throw new Exception("非字符串类型的属性不能使用HtmlEncodeAttribute修饰");
			}
		}

		public static string HtmlDecode(string textToFormat)
		{
    
			if (string.IsNullOrEmpty(textToFormat))
			{
    
				return textToFormat;
			}
			return HttpUtility.HtmlDecode(textToFormat);
		}

		public static string HtmlEncode(string textToFormat)
		{
    
			if (string.IsNullOrEmpty(textToFormat))
			{
    
				return textToFormat;
			}
			return HttpUtility.HtmlEncode(textToFormat);
		}

		public static string UrlEncode(string urlToEncode)
		{
    
			if (string.IsNullOrEmpty(urlToEncode))
			{
    
				return urlToEncode;
			}
			return HttpUtility.UrlEncode(urlToEncode, Encoding.UTF8);
		}

		public static string UrlDecode(string urlToDecode)
		{
    
			if (string.IsNullOrEmpty(urlToDecode))
			{
    
				return urlToDecode;
			}
			return HttpUtility.UrlDecode(urlToDecode, Encoding.UTF8);
		}

		public static string StripScriptTags(string content)
		{
    
			content = Regex.Replace(content, "<script((.|\n)*?)</script>", "", RegexOptions.IgnoreCase | RegexOptions.Multiline);
			content = Regex.Replace(content, "'javascript:", "", RegexOptions.IgnoreCase | RegexOptions.Multiline);
			return Regex.Replace(content, "\"javascript:", "", RegexOptions.IgnoreCase | RegexOptions.Multiline);
		}

		public static string StripAllTags(string strToStrip)
		{
    
			if (!string.IsNullOrEmpty(strToStrip))
			{
    
				strToStrip = Regex.Replace(strToStrip, "</p(?:\\s*)>(?:\\s*)<p(?:\\s*)>", "\n\n", RegexOptions.IgnoreCase | RegexOptions.Compiled);
				strToStrip = Regex.Replace(strToStrip, "<br(?:\\s*)/>", "\n", RegexOptions.IgnoreCase | RegexOptions.Compiled);
				strToStrip = Regex.Replace(strToStrip, "\"", "''", RegexOptions.IgnoreCase | RegexOptions.Compiled);
				strToStrip = Globals.StripHtmlXmlTags(strToStrip);
			}
			return strToStrip;
		}

		public static string StripHtmlXmlTags(string content)
		{
    
			return Regex.Replace(content, "<[^>]+>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
		}

		public static string HostPath(Uri uri)
		{
    
			if (uri == (Uri)null)
			{
    
				return string.Empty;
			}
			string text = (uri.Port == 80) ? string.Empty : (":" + uri.Port.ToString(CultureInfo.InvariantCulture));
			return string.Format(CultureInfo.InvariantCulture, "{0}://{1}{2}", new object[3]
			{
    
				uri.Scheme,
				uri.Host,
				text
			});
		}

		public static string HttpsHostPath(Uri uri)
		{
    
			if (uri == (Uri)null)
			{
    
				return string.Empty;
			}
			string text = "";
			return string.Format(CultureInfo.InvariantCulture, "{2}://{0}{1}", new object[3]
			{
    
				uri.Host,
				text,
				"https"
			});
		}

		public static string FullPath(string local)
		{
    
			if (string.IsNullOrEmpty(local))
			{
    
				return local;
			}
			if (local.ToLower(CultureInfo.InvariantCulture).StartsWith("http://") || local.ToLower(CultureInfo.InvariantCulture).StartsWith("https://"))
			{
    
				return local;
			}
			if (HttpContext.Current == null)
			{
    
				return local;
			}
			if (local.ToLower(CultureInfo.InvariantCulture).StartsWith(HttpContext.Current.Request.Url.Host.ToLower(CultureInfo.InvariantCulture)))
			{
    
				return string.Format(CultureInfo.InvariantCulture, "{0}://{1}", new object[2]
				{
    
					Globals.GetProtocal(null),
					local
				});
			}
			return Globals.FullPath(Globals.HostPath(HttpContext.Current.Request.Url), local);
		}

		public static string HttpsFullPath(string local)
		{
    
			if (string.IsNullOrEmpty(local))
			{
    
				return local;
			}
			if (local.ToLower(CultureInfo.InvariantCulture).StartsWith("http://") || local.ToLower(CultureInfo.InvariantCulture).StartsWith("https://"))
			{
    
				return local;
			}
			if (HttpContext.Current == null)
			{
    
				return local;
			}
			if (local.ToLower(CultureInfo.InvariantCulture).StartsWith(HttpContext.Current.Request.Url.Host.ToLower(CultureInfo.InvariantCulture)))
			{
    
				return string.Format(CultureInfo.InvariantCulture, "https://{0}", new object[1]
				{
    
					local
				});
			}
			return Globals.FullPath(Globals.HttpsHostPath(HttpContext.Current.Request.Url), local);
		}

		public static string FullPath(string hostPath, string local)
		{
    
			return hostPath + local;
		}


		public static string FormatMoney(decimal money)
		{
    
			return string.Format(CultureInfo.InvariantCulture, "{0}", new object[1]
			{
    
				money.F2ToString("f2")
			});
		}

		public static string GetphysicsPath(string path)
		{
    
			string text = "";
			try
			{
    
				if (HttpContext.Current == null)
				{
    
					string text2 = path.Replace("/", "\\");
					if (text2.StartsWith("\\"))
					{
    
						text2 = text2.TrimStart('\\');
					}
					return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, text2);
				}
				return HttpContext.Current.Request.MapPath(path);
			}
			catch
			{
    
				return path;
			}
		}

		public static string GetphysicsPath(string path, out bool CheckExist)
		{
    
			CheckExist = true;
			string text = Globals.GetphysicsPath(path);
			if (CheckExist)
			{
    
				if (text.EndsWith(Path.DirectorySeparatorChar.ToString()))
				{
    
					if (!Directory.Exists(text))
					{
    
						CheckExist = false;
					}
				}
				else if (!File.Exists(text))
				{
    
					CheckExist = false;
				}
			}
			return text;
		}

		public static bool PathExist(string path, bool CreatePath = false)
		{
    
			bool flag = false;
			path = Globals.GetphysicsPath(path, out flag);
			string[] array = path.Split(Path.DirectorySeparatorChar);
			string text = array[0];
			int num = array.Length;
			if (array.Length >= 1 && array[array.Length - 1].Contains("."))
			{
    
				num--;
			}
			if (CreatePath && !flag)
			{
    
				for (int i = 1; i < num; i++)
				{
    
					if (!string.IsNullOrEmpty(array[i]))
					{
    
						text = text + Path.DirectorySeparatorChar.ToString() + array[i];
						try
						{
    
							if (!Directory.Exists(text))
							{
    
								Directory.CreateDirectory(text);
							}
						}
						catch (Exception)
						{
    
						}
					}
				}
			}
			return flag;
		}

		public static bool CreatePath(string path)
		{
    
			bool result = true;
			path = Globals.GetphysicsPath(path).ToLower();
			string text = AppDomain.CurrentDomain.BaseDirectory.ToLower();
			path = path.Replace(text, "");
			string[] array = path.Split(Path.DirectorySeparatorChar);
			string str = array[0];
			str = text + str;
			int num = array.Length;
			if (array.Length >= 1 && array[array.Length - 1].Contains("."))
			{
    
				num--;
			}
			try
			{
    
				for (int i = 1; i < num; i++)
				{
    
					if (!string.IsNullOrEmpty(array[i]))
					{
    
						str = str + Path.DirectorySeparatorChar.ToString() + array[i];
						if (!Directory.Exists(str))
						{
    
							Directory.CreateDirectory(str);
						}
					}
				}
			}
			catch (Exception)
			{
    
				result = false;
			}
			return result;
		}

		public static string GetGenerateId()
		{
    
			string text = string.Empty;
			Random random = new Random();
			for (int i = 0; i < 7; i++)
			{
    
				int num = random.Next();
				text += ((char)(ushort)(48 + (ushort)(num % 10))).ToString();
			}
			return DateTime.Now.ToString("yyyyMMdd") + text;
		}

		public static void WriteLog(IDictionary<string, string> param, string msg, string sign = "", string url = "", string logPath = "")
		{
    
			try
			{
    
				Globals.CreatePath("/log");
				DateTime now;
				if (string.IsNullOrEmpty(logPath))
				{
    
					now = DateTime.Now;
					logPath = "/log/error_" + now.ToString("yyyyMMddHHmm") + ".xml";
				}
				else if (logPath.IndexOf('/') == -1 && logPath.IndexOf('.') == -1)
				{
    
					string[] obj = new string[5]
					{
    
						"/log/",
						logPath,
						"_",
						null,
						null
					};
					now = DateTime.Now;
					obj[3] = now.ToString("yyyyMMddHHmm");
					obj[4] = ".xml";
					logPath = string.Concat(obj);
				}
				DataTable dataTable = new DataTable();
				dataTable.TableName = "log";
				dataTable.Columns.Add(new DataColumn("HishopOperTime"));
				if (param != null)
				{
    
					foreach (KeyValuePair<string, string> item in param)
					{
    
						dataTable.Columns.Add(new DataColumn(item.Key));
					}
				}
				dataTable.Columns.Add(new DataColumn("HishopMsg"));
				if (!string.IsNullOrEmpty(sign))
				{
    
					dataTable.Columns.Add(new DataColumn("HishopSign"));
				}
				if (!string.IsNullOrEmpty(url))
				{
    
					dataTable.Columns.Add(new DataColumn("HishopUrl"));
				}
				DataRow dataRow = dataTable.NewRow();
				dataRow["HishopOperTime"] = DateTime.Now;
				foreach (KeyValuePair<string, string> item2 in param)
				{
    
					dataRow[item2.Key] = item2.Value;
				}
				dataRow["HishopMsg"] = msg;
				if (!string.IsNullOrEmpty(sign))
				{
    
					dataRow["HishopSign"] = sign;
				}
				if (!string.IsNullOrEmpty(url))
				{
    
					dataRow["HishopUrl"] = url;
				}
				dataTable.Rows.Add(dataRow);
				string fileName = Globals.GetphysicsPath(logPath);
				dataTable.WriteXml(fileName);
			}
			catch (Exception innerException)
			{
    
				throw new Exception("写日志失败:" + logPath, innerException);
			}
		}

		public static void WriteLog(NameValueCollection param, string msg, string sign = "", string url = "", string logPath = "")
		{
    
			try
			{
    
				Globals.CreatePath("/log");
				DateTime now;
				if (string.IsNullOrEmpty(logPath))
				{
    
					now = DateTime.Now;
					logPath = "/log/error_" + now.ToString("yyyyMMddHHmm") + ".xml";
				}
				else if (logPath.IndexOf('/') == -1 && logPath.IndexOf('.') == -1)
				{
    
					string[] obj = new string[5]
					{
    
						"/log/",
						logPath,
						"_",
						null,
						null
					};
					now = DateTime.Now;
					obj[3] = now.ToString("yyyyMMddHHmm");
					obj[4] = ".xml";
					logPath = string.Concat(obj);
				}
				DataTable dataTable = new DataTable();
				dataTable.TableName = "log";
				dataTable.Columns.Add(new DataColumn("HishopOperTime"));
				if (param != null)
				{
    
					string[] allKeys = param.AllKeys;
					foreach (string columnName in allKeys)
					{
    
						dataTable.Columns.Add(new DataColumn(columnName));
					}
				}
				dataTable.Columns.Add(new DataColumn("HishopMsg"));
				if (!string.IsNullOrEmpty(sign))
				{
    
					dataTable.Columns.Add(new DataColumn("HishopSign"));
				}
				if (!string.IsNullOrEmpty(url))
				{
    
					dataTable.Columns.Add(new DataColumn("HishopUrl"));
				}
				DataRow dataRow = dataTable.NewRow();
				dataRow["HishopOperTime"] = DateTime.Now;
				string[] allKeys2 = param.AllKeys;
				foreach (string text in allKeys2)
				{
    
					dataRow[text] = param[text];
				}
				dataRow["HishopMsg"] = msg;
				if (!string.IsNullOrEmpty(sign))
				{
    
					dataRow["HishopSign"] = sign;
				}
				if (!string.IsNullOrEmpty(url))
				{
    
					dataRow["HishopUrl"] = url;
				}
				dataTable.Rows.Add(dataRow);
				string fileName = Globals.GetphysicsPath(logPath);
				dataTable.WriteXml(fileName);
			}
			catch (Exception innerException)
			{
    
				throw new Exception("写日志失败:" + logPath, innerException);
			}
		}

		public static void WriteLog(string msg, string sign = "", string url = "", string logPath = "")
		{
    
			try
			{
    
				Globals.CreatePath("/log");
				DateTime now;
				if (string.IsNullOrEmpty(logPath))
				{
    
					now = DateTime.Now;
					logPath = "/log/error_" + now.ToString("yyyyMMddHHmm") + ".xml";
				}
				else if (logPath.IndexOf('/') == -1 && logPath.IndexOf('.') == -1)
				{
    
					string[] obj = new string[5]
					{
    
						"/log/",
						logPath,
						"_",
						null,
						null
					};
					now = DateTime.Now;
					obj[3] = now.ToString("yyyyMMddHHmm");
					obj[4] = ".xml";
					logPath = string.Concat(obj);
				}
				DataTable dataTable = new DataTable();
				dataTable.TableName = "log";
				dataTable.Columns.Add(new DataColumn("HishopOperTime"));
				dataTable.Columns.Add(new DataColumn("HishopMsg"));
				if (!string.IsNullOrEmpty(sign))
				{
    
					dataTable.Columns.Add(new DataColumn("HishopSign"));
				}
				if (!string.IsNullOrEmpty(url))
				{
    
					dataTable.Columns.Add(new DataColumn("HishopUrl"));
				}
				DataRow dataRow = dataTable.NewRow();
				dataRow["HishopOperTime"] = DateTime.Now;
				dataRow["HishopMsg"] = msg;
				if (!string.IsNullOrEmpty(sign))
				{
    
					dataRow["HishopSign"] = sign;
				}
				if (!string.IsNullOrEmpty(url))
				{
    
					dataRow["HishopUrl"] = url;
				}
				dataTable.Rows.Add(dataRow);
				string fileName = Globals.GetphysicsPath(logPath);
				dataTable.WriteXml(fileName);
			}
			catch (Exception innerException)
			{
    
				throw new Exception("写日志失败:" + logPath, innerException);
			}
		}

		public static void AppendLog(IDictionary<string, string> param, string msg, string sign = "", string url = "", string logPath = "")
		{
    
			object obj = new object();
			lock (obj)
			{
    
				DateTime now;
				if (string.IsNullOrEmpty(logPath))
				{
    
					now = DateTime.Now;
					logPath = "/log/error_" + now.ToString("yyyyMMddHHmm") + ".txt";
				}
				else if (logPath.IndexOf('/') == -1 && logPath.IndexOf('.') == -1)
				{
    
					string[] obj2 = new string[5]
					{
    
						"/log/",
						logPath,
						"_",
						null,
						null
					};
					now = DateTime.Now;
					obj2[3] = now.ToString("yyyyMMddHHmm");
					obj2[4] = ".txt";
					logPath = string.Concat(obj2);
				}
				string path = Globals.GetphysicsPath(logPath);
				Globals.CreatePath(path);
				using (StreamWriter streamWriter = File.AppendText(path))
				{
    
					StreamWriter streamWriter2 = streamWriter;
					now = DateTime.Now;
					streamWriter2.WriteLine("时间:" + now.ToString());
					if (param != null)
					{
    
						foreach (KeyValuePair<string, string> item in param)
						{
    
							streamWriter.WriteLine(item.Key + ":" + item.Value);
						}
					}
					if (!string.IsNullOrEmpty(url))
					{
    
						streamWriter.WriteLine("HishopLogUrl:" + url);
					}
					if (!string.IsNullOrEmpty(sign))
					{
    
						streamWriter.WriteLine("HishopLogSign:" + sign);
					}
					streamWriter.WriteLine("HishopLogMsg:" + msg);
					streamWriter.WriteLine("");
					streamWriter.WriteLine("");
				}
			}
		}

		public static void AppendLog(NameValueCollection param, string msg, string sign = "", string url = "", string logPath = "")
		{
    
			object obj = new object();
			lock (obj)
			{
    
				DateTime now;
				if (string.IsNullOrEmpty(logPath))
				{
    
					now = DateTime.Now;
					logPath = "/log/error_" + now.ToString("yyyyMMddHHmm") + ".txt";
				}
				else if (logPath.IndexOf('/') == -1 && logPath.IndexOf('.') == -1)
				{
    
					string[] obj2 = new string[5]
					{
    
						"/log/",
						logPath,
						"_",
						null,
						null
					};
					now = DateTime.Now;
					obj2[3] = now.ToString("yyyyMMddHHmm");
					obj2[4] = ".txt";
					logPath = string.Concat(obj2);
				}
				string path = Globals.GetphysicsPath(logPath);
				Globals.CreatePath(path);
				using (StreamWriter streamWriter = File.AppendText(path))
				{
    
					StreamWriter streamWriter2 = streamWriter;
					now = DateTime.Now;
					streamWriter2.WriteLine("时间:" + now.ToString());
					if (param != null)
					{
    
						string[] allKeys = param.AllKeys;
						foreach (string text in allKeys)
						{
    
							streamWriter.WriteLine(text + ":" + param[text]);
						}
					}
					if (!string.IsNullOrEmpty(url))
					{
    
						streamWriter.WriteLine("HishopUrl:" + url);
					}
					if (!string.IsNullOrEmpty(sign))
					{
    
						streamWriter.WriteLine("HishopSign:" + sign);
					}
					streamWriter.WriteLine("Hishopmsg:" + msg);
					streamWriter.WriteLine("");
					streamWriter.WriteLine("");
				}
			}
		}

		public static void AppendLog(string msg, string sign = "", string url = "", string logPath = "")
		{
    
			object obj = new object();
			lock (obj)
			{
    
				DateTime now;
				if (string.IsNullOrEmpty(logPath))
				{
    
					now = DateTime.Now;
					logPath = "/log/error_" + now.ToString("yyyyMMddHHmm") + ".txt";
				}
				else if (logPath.IndexOf('/') == -1 && logPath.IndexOf('.') == -1)
				{
    
					string[] obj2 = new string[5]
					{
    
						"/log/",
						logPath,
						"_",
						null,
						null
					};
					now = DateTime.Now;
					obj2[3] = now.ToString("yyyyMMddHHmm");
					obj2[4] = ".txt";
					logPath = string.Concat(obj2);
				}
				string path = Globals.GetphysicsPath(logPath);
				Globals.CreatePath(path);
				using (StreamWriter streamWriter = File.AppendText(path))
				{
    
					StreamWriter streamWriter2 = streamWriter;
					now = DateTime.Now;
					streamWriter2.WriteLine("时间:" + now.ToString());
					if (!string.IsNullOrEmpty(url))
					{
    
						streamWriter.WriteLine("HishopUrl:" + url);
					}
					if (!string.IsNullOrEmpty(sign))
					{
    
						streamWriter.WriteLine("HishopSign:" + sign);
					}
					streamWriter.WriteLine("Hishopmsg:" + msg);
					streamWriter.WriteLine("");
					streamWriter.WriteLine("");
				}
			}
		}

		public static string RndStr(int length)
		{
    
			Random random = new Random();
			string text = "";
			for (int i = 1; i <= length; i++)
			{
    
				text += random.Next(0, 9).ToString();
			}
			return text;
		}

		public static string GetHiddenStr(int len, string hidStr = "*")
		{
    
			string text = "";
			for (int i = 0; i < len; i++)
			{
    
				text += "*";
			}
			return text;
		}

		public static string RndStr(int length, bool IsUpper)
		{
    
			Random random = new Random();
			string text = "";
			int i = 1;
			char c;
			if (IsUpper)
			{
    
				for (; i <= length; i++)
				{
    
					string str = text;
					c = (char)random.Next(65, 91);
					text = str + c.ToString();
				}
			}
			else
			{
    
				for (; i <= length; i++)
				{
    
					string str2 = text;
					c = (char)random.Next(97, 122);
					text = str2 + c.ToString();
				}
			}
			return text;
		}

		public static string GetXmlNodeValue(string configXML, string nodeName)
		{
    
			string result = "";
			XmlDocument xmlDocument = new XmlDocument();
			try
			{
    
				xmlDocument.LoadXml(configXML);
				XmlNode documentElement = xmlDocument.DocumentElement;
				XmlNode xmlNode = documentElement.SelectSingleNode(nodeName);
				if (xmlNode != null)
				{
    
					result = xmlNode.InnerText;
				}
			}
			catch
			{
    
			}
			return result;
		}

		public static string GetResponseResult(string url)
		{
    
			try
			{
    
				WebRequest webRequest = WebRequest.Create(url);
				using (HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse())
				{
    
					using (Stream stream = httpWebResponse.GetResponseStream())
					{
    
						using (StreamReader streamReader = new StreamReader(stream, Encoding.UTF8))
						{
    
							return streamReader.ReadToEnd();
						}
					}
				}
			}
			catch (Exception ex)
			{
    
				IDictionary<string, string> dictionary = new Dictionary<string, string>();
				dictionary.Add("Url", url);
				Globals.WriteExceptionLog(ex, dictionary, "GetResponseResult");
				return "";
			}
		}

		public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
		{
    
			return true;
		}

		public static string GetPostResult(string url, string postData)
		{
    
			string result = string.Empty;
			try
			{
    
				Uri requestUri = new Uri(url);
				ServicePointManager.ServerCertificateValidationCallback = Globals.CheckValidationResult;
				HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
				Encoding uTF = Encoding.UTF8;
				byte[] bytes = uTF.GetBytes(postData);
				httpWebRequest.Method = "POST";
				httpWebRequest.ContentType = "application/x-www-form-urlencoded";
				httpWebRequest.ContentLength = bytes.Length;
				using (Stream stream = httpWebRequest.GetRequestStream())
				{
    
					stream.Write(bytes, 0, bytes.Length);
				}
				using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
				{
    
					using (Stream stream2 = httpWebResponse.GetResponseStream())
					{
    
						Encoding uTF2 = Encoding.UTF8;
						Stream stream3 = stream2;
						if (httpWebResponse.ContentEncoding.ToLower() == "gzip")
						{
    
							stream3 = new GZipStream(stream2, CompressionMode.Decompress);
						}
						else if (httpWebResponse.ContentEncoding.ToLower() == "deflate")
						{
    
							stream3 = new DeflateStream(stream2, CompressionMode.Decompress);
						}
						using (StreamReader streamReader = new StreamReader(stream3, uTF2))
						{
    
							result = streamReader.ReadToEnd();
						}
					}
				}
			}
			catch (Exception ex)
			{
    
				IDictionary<string, string> dictionary = new Dictionary<string, string>();
				dictionary.Add("Url", url);
				dictionary.Add("PostData", postData);
				Globals.WriteExceptionLog(ex, dictionary, "GetPostResult");
				result = "";
			}
			return result;
		}

		public static string GetStringByRegularExpression(string input, string pattern)
		{
    
			StringBuilder stringBuilder = new StringBuilder();
			foreach (Match item in Regex.Matches(input, pattern))
			{
    
				stringBuilder.Append(item.Value);
			}
			return stringBuilder.ToString();
		}

		public static long DateTimeToUnixTimestamp(DateTime dateTime)
		{
    
			DateTime d = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
			return Convert.ToInt64((dateTime - d).TotalSeconds);
		}

		public static DateTime UnixTimestampToDateTime(this DateTime target, long timestamp)
		{
    
			DateTime dateTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
			long ticks = long.Parse(timestamp + "0000000");
			TimeSpan value = new TimeSpan(ticks);
			return dateTime.Add(value);
		}

		public static void DeleteFolder(string targetFolderName, bool isReservedFolder = false, string defaultFolder = "/Storage/master/")
		{
    
			string path = defaultFolder + targetFolderName;
			string path2 = $"{
      HttpContext.Current.Server.MapPath(path)}";
			DirectoryInfo directoryInfo = new DirectoryInfo(path2);
			if (directoryInfo.Exists)
			{
    
				directoryInfo.Delete(true);
				directoryInfo = new DirectoryInfo(path2);
				if (!directoryInfo.Exists & isReservedFolder)
				{
    
					Directory.CreateDirectory(path2);
				}
			}
		}

		public static string SaveFile(string targetFolderName, string fileURL, string defaultFolder = "/Storage/master/", bool overwrite = true, bool physicalPath = false, string additiveFileName = "")
		{
    
			if (fileURL.IndexOf("/temp/") < 0)
			{
    
				return fileURL;
			}
			string empty = string.Empty;
			string text = defaultFolder + targetFolderName + "\\";
			string text2 = $"{
      HttpContext.Current.Server.MapPath(text)}";
			if (!Globals.PathExist(text2, false))
			{
    
				Globals.CreatePath(text2);
			}
			string str = (fileURL.Split('/').Length == 6) ? fileURL.Split('/')[5] : fileURL.Split('/')[4];
			if (!string.IsNullOrEmpty(additiveFileName))
			{
    
				str = additiveFileName + str;
			}
			string text3 = text2 + str;
			string text4 = HttpContext.Current.Server.MapPath(fileURL);
			if (File.Exists(text4))
			{
    
				File.Copy(text4, text3, overwrite);
			}
			empty = (physicalPath ? text3 : (text + str));
			string path = HttpContext.Current.Server.MapPath(fileURL);
			if (File.Exists(path))
			{
    
				File.Delete(path);
			}
			return empty.Replace("\\", "/").Replace("//", "/");
		}

		public static string CreateQRCode(string content, string qrCodeUrl, bool IsOverWrite = false, ImageFormats imgFomrats = ImageFormats.Png)
		{
    
			try
			{
    
				ImageFormat png = ImageFormat.Png;
				switch (imgFomrats)
				{
    
					case ImageFormats.Bmp:
						png = ImageFormat.Bmp;
						break;
					case ImageFormats.Emf:
						png = ImageFormat.Emf;
						break;
					case ImageFormats.Exif:
						png = ImageFormat.Exif;
						break;
					case ImageFormats.Gif:
						png = ImageFormat.Gif;
						break;
					case ImageFormats.Icon:
						png = ImageFormat.Icon;
						break;
					case ImageFormats.Jpeg:
						png = ImageFormat.Jpeg;
						break;
					case ImageFormats.MemoryBmp:
						png = ImageFormat.MemoryBmp;
						break;
					case ImageFormats.Png:
						png = ImageFormat.Png;
						break;
					case ImageFormats.Tiff:
						png = ImageFormat.Tiff;
						break;
					case ImageFormats.Wmf:
						png = ImageFormat.Wmf;
						break;
					default:
						png = ImageFormat.Png;
						break;
				}
				qrCodeUrl = qrCodeUrl.Replace("\\", "/");
				string path = qrCodeUrl.Substring(0, qrCodeUrl.LastIndexOf('/'));
				string text = Globals.GetphysicsPath(qrCodeUrl);
				if (File.Exists(text) && !IsOverWrite)
				{
    
					return qrCodeUrl;
				}
				QRCodeEncoder qRCodeEncoder = new QRCodeEncoder();
				qRCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
				qRCodeEncoder.QRCodeScale = 10;
				qRCodeEncoder.QRCodeVersion = 0;
				qRCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
				string path2 = Globals.GetphysicsPath(path);
				Bitmap bitmap = qRCodeEncoder.Encode(content);
				if (Directory.Exists(path2))
				{
    
					bitmap.Save(text, png);
				}
				else
				{
    
					Globals.CreatePath(path);
					bitmap.Save(text, png);
				}
				bitmap.Dispose();
			}
			catch (Exception ex)
			{
    
				Globals.WriteExceptionLog(ex, null, "CreateQrCode");
			}
			return qrCodeUrl;
		}

		public static MemoryStream GenerateTwoDimensionalImage(string url)
		{
    
			QRCodeEncoder qRCodeEncoder = new QRCodeEncoder();
			qRCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
			qRCodeEncoder.QRCodeScale = 10;
			qRCodeEncoder.QRCodeVersion = 0;
			qRCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
			Bitmap bitmap = qRCodeEncoder.Encode(url);
			MemoryStream memoryStream = new MemoryStream();
			bitmap.Save(memoryStream, ImageFormat.Png);
			return memoryStream;
		}

		public static bool ValidateCertFile(string fileName)
		{
    
			fileName = fileName.ToUpper();
			if (fileName.Contains(".CRT") || fileName.Contains(".CER") || fileName.Contains(".P12") || fileName.Contains(".P7B") || fileName.Contains(".P7C") || fileName.Contains(".SPC") || fileName.Contains(".KEY") || fileName.Contains(".DER") || fileName.Contains(".PEM") || fileName.Contains(".PFX"))
			{
    
				return true;
			}
			return false;
		}

		public static string GetEmailSafeStr(string email, int start, int len)
		{
    
			if (string.IsNullOrEmpty(email))
			{
    
				return "";
			}
			string str = email.Split('@')[0];
			str = Globals.GetSafeStr(str, start, len);
			if (DataHelper.IsEmail(email))
			{
    
				return str + "@" + email.Split('@')[1];
			}
			return str;
		}

		public static string GetSafeStr(string str, int start, int len)
		{
    
			if (start > str.Length || start < 0)
			{
    
				return str;
			}
			if (str.Length > start + len && len > 0)
			{
    
				return str.Substring(0, start) + Globals.GetHideStr(len, "*") + str.Substring(start + len);
			}
			if (len == 0)
			{
    
				len = str.Length - start;
			}
			return str.Substring(0, start) + Globals.GetHideStr(len, "*");
		}

		private static string GetHideStr(int len, string hideChar = "*")
		{
    
			string text = "";
			for (int i = 0; i < len; i++)
			{
    
				text += hideChar;
			}
			return text;
		}

		public static string GetHideUserName(string str)
		{
    
			if (str.Length <= 1)
			{
    
				return str;
			}
			return str.Substring(0, 1) + Globals.GetHideStr(3, "*") + str.Substring(str.Length - 1);
		}

		public static IDictionary<string, string> NameValueCollectionToDictionary(NameValueCollection collection)
		{
    
			IDictionary<string, string> dictionary = new Dictionary<string, string>();
			if (collection == null && collection.AllKeys.Length == 0)
			{
    
				return dictionary;
			}
			string[] allKeys = collection.AllKeys;
			foreach (string text in allKeys)
			{
    
				if (!string.IsNullOrEmpty(text) && !dictionary.ContainsKey(text))
				{
    
					dictionary.Add(new KeyValuePair<string, string>(text, collection[text]));
				}
			}
			return dictionary;
		}

		public static void WriteExceptionLog_Page(Exception ex, NameValueCollection param, string fileName = "Exception")
		{
    
			IDictionary<string, string> dictionary = Globals.NameValueCollectionToDictionary(param);
			if (!(ex is ThreadAbortException))
			{
    
				dictionary.Add("ErrorMessage", ex.Message);
				dictionary.Add("StackTrace", ex.StackTrace);
				if (ex.InnerException != null)
				{
    
					dictionary.Add("InnerException", ex.InnerException.ToString());
				}
				if (ex.GetBaseException() != null)
				{
    
					dictionary.Add("BaseException", ex.GetBaseException().Message);
				}
				if (ex.TargetSite != (MethodBase)null)
				{
    
					dictionary.Add("TargetSite", ex.TargetSite.ToString());
				}
				dictionary.Add("ExSource", ex.Source);
				string url = "";
				if (HttpContext.Current != null)
				{
    
					url = HttpContext.Current.Request.Url.ToString();
				}
				Globals.AppendLog(dictionary, "", "", url, fileName);
			}
		}

		public static void WriteExceptionLog(Exception ex, IDictionary<string, string> iParam = null, string fileName = "Exception")
		{
    
			if (iParam == null)
			{
    
				iParam = new Dictionary<string, string>();
			}
			if (!(ex is ThreadAbortException))
			{
    
				iParam.Add("ErrorMessage", ex.Message);
				iParam.Add("StackTrace", ex.StackTrace);
				if (ex.InnerException != null)
				{
    
					iParam.Add("InnerException", ex.InnerException.ToString());
				}
				if (ex.GetBaseException() != null)
				{
    
					iParam.Add("BaseException", ex.GetBaseException().Message);
				}
				if (ex.TargetSite != (MethodBase)null)
				{
    
					iParam.Add("TargetSite", ex.TargetSite.ToString());
				}
				iParam.Add("ExSource", ex.Source);
				string url = "";
				if (HttpContext.Current != null)
				{
    
					url = HttpContext.Current.Request.Url.ToString();
				}
				Globals.AppendLog(iParam, "", "", url, fileName);
			}
		}

		public static string GetProtocal(HttpContext context = null)
		{
    
			if (context != null)
			{
    
				return context.Request.IsSecureConnection ? "https" : "http";
			}
			context = HttpContext.Current;
			return (context == null || !context.Request.IsSecureConnection) ? "http" : "https";
		}
		public static string ToNullString(this object obj)
		{
    
			return (obj == null && obj != DBNull.Value) ? string.Empty : obj.ToString().Trim();
		}

		public static string F2ToString(this object obj, string format = "f2")
		{
    
			if (obj == null)
			{
    
				return "";
			}
			if ((obj.IsDecimal() || obj.IsDouble() || obj.IsInt() || obj.IsFloat()) && (format == "f2" || format == "F2"))
			{
    
				string text = obj.ToNullString();
				int length = obj.ToNullString().Length;
				int num = obj.ToNullString().LastIndexOf(".");
				string text2 = "";
				if (num > -1)
				{
    
					switch (length - num)
					{
    
						case 1:
							text2 = text + "00";
							break;
						case 2:
							text2 = text + "0";
							break;
						case 3:
							text2 = text;
							break;
						default:
							text2 = text.Substring(0, num + 3);
							break;
					}
				}
				else
				{
    
					text2 = text + ".00";
				}
				return text2;
			}
			return obj.ToString();
		}

		public static bool IsDecimal(this object obj)
		{
    
			decimal num = default(decimal);
			return decimal.TryParse(obj.ToNullString(), out num);
		}

		public static bool IsDouble(this object obj)
		{
    
			double num = 0.0;
			return double.TryParse(obj.ToNullString(), out num);
		}

		public static bool IsFloat(this object obj)
		{
    
			float num = 0f;
			return float.TryParse(obj.ToNullString(), out num);
		}

		public static bool IsInt(this object obj)
		{
    
			int num = 0;
			return int.TryParse(obj.ToNullString(), out num);
		}

		public static bool IsPositiveInteger(this object obj)
		{
    
			return Regex.IsMatch(obj.ToNullString(), "[0-9]\\d*");
		}
	}

HttpClient 方式

 		/// <summary>
        /// 发起请求
        /// </summary>
        /// <param name="Url">请求路径</param>
        /// <returns></returns>
   private async Task<T> Response<T>(IBaseReq<T> request, string Url, ResponseType RType = ResponseType.Post) where T : BaseRes
        {
    
            var rspModel = Activator.CreateInstance<T>();
            try
            {
    
                var url = serverUrl + Url;
                Dictionary<string, object> parames = new Dictionary<string, object>();
                if (request != null)
                {
    
                    parames = JsonConvert.DeserializeObject<Dictionary<string, object>>(JsonConvert.SerializeObject(request)) ?? new Dictionary<string, object>();
                }
                using (var client = new HttpClient())
                {
    
                    client.DefaultRequestHeaders.Add("sign", Sign(parames));//添加请求头
                    client.DefaultRequestHeaders.Add("timestamp", timeStamp().ToString());
                    client.DefaultRequestHeaders.Add("key", appKey);
                    client.Timeout = TimeSpan.FromSeconds(30);//设置超时时间
                    HttpResponseMessage response = new HttpResponseMessage();
                    switch (RType)
                    {
    
                        case ResponseType.Post:
                            response = client.PostAsync(url, new StringContent(JsonConvert.SerializeObject(parames), Encoding.UTF8, "application/json")).Result;
                            break;
                        case ResponseType.Put:
                            response = client.PutAsync(url, new StringContent(JsonConvert.SerializeObject(parames), Encoding.UTF8, "application/json")).Result;
                            break;
                        case ResponseType.Delete:
                            response = client.DeleteAsync(url + "?" + buildParamStr(parames)).Result;
                            break;
                        case ResponseType.Get:
                            response = client.GetAsync(url + "?" + buildParamStr(parames)).Result;
                            break;
                        default:
                            rspModel.Code = 1;
                            rspModel.Msg = "请求类型错误!";
                            break;
                    }
                    if (response != null && response.IsSuccessStatusCode)
                    {
    
                        string responseText = response.Content.ReadAsStringAsync().Result;
                        if (!string.IsNullOrWhiteSpace(responseText))
                        {
    
                            if (responseText.Contains("签名"))
                            {
    
                                SginErroRes erroRes = JsonConvert.DeserializeObject<SginErroRes>(responseText);
                                rspModel.Msg = erroRes.Msg;
                                rspModel.Time=erroRes.Time;
                            }
                            else
                            {
    
                                rspModel = JsonConvert.DeserializeObject<T>(responseText);
                            }
                        }
                        else
                        {
    
                            rspModel.Msg = "返回内容为空!";

                        }


                    }

                };
            }
            catch (Exception ex)
            {
    
                rspModel.Code = 1;
                rspModel.Msg = ex.Message;
            }


            return rspModel;
        }

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_42455262/article/details/115328006

智能推荐

51单片机的中断系统_51单片机中断篇-程序员宅基地

文章浏览阅读3.3k次,点赞7次,收藏39次。CPU 执行现行程序的过程中,出现某些急需处理的异常情况或特殊请求,CPU暂时中止现行程序,而转去对异常情况或特殊请求进行处理,处理完毕后再返回现行程序断点处,继续执行原程序。void 函数名(void) interrupt n using m {中断函数内容 //尽量精简 }编译器会把该函数转化为中断函数,表示中断源编号为n,中断源对应一个中断入口地址,而中断入口地址的内容为跳转指令,转入本函数。using m用于指定本函数内部使用的工作寄存器组,m取值为0~3。该修饰符可省略,由编译器自动分配。_51单片机中断篇

oracle项目经验求职,网络工程师简历中的项目经验怎么写-程序员宅基地

文章浏览阅读396次。项目经验(案例一)项目时间:2009-10 - 2009-12项目名称:中驰别克信息化管理整改完善项目描述:项目介绍一,建立中驰别克硬件档案(PC,服务器,网络设备,办公设备等)二,建立中驰别克软件档案(每台PC安装的软件,财务,HR,OA,专用系统等)三,能过建立的档案对中驰别克信息化办公环境优化(合理使用ADSL宽带资源,对域进行调整,对文件服务器进行优化,对共享打印机进行调整)四,优化完成后..._网络工程师项目经历

LVS四层负载均衡集群-程序员宅基地

文章浏览阅读1k次,点赞31次,收藏30次。LVS:Linux Virtual Server,负载调度器,内核集成, 阿里的四层SLB(Server Load Balance)是基于LVS+keepalived实现。NATTUNDR优点端口转换WAN性能最好缺点性能瓶颈服务器支持隧道模式不支持跨网段真实服务器要求anyTunneling支持网络private(私网)LAN/WAN(私网/公网)LAN(私网)真实服务器数量High (100)High (100)真实服务器网关lvs内网地址。

「技术综述」一文道尽传统图像降噪方法_噪声很大的图片可以降噪吗-程序员宅基地

文章浏览阅读899次。https://www.toutiao.com/a6713171323893318151/作者 | 黄小邪/言有三编辑 | 黄小邪/言有三图像预处理算法的好坏直接关系到后续图像处理的效果,如图像分割、目标识别、边缘提取等,为了获取高质量的数字图像,很多时候都需要对图像进行降噪处理,尽可能的保持原始信息完整性(即主要特征)的同时,又能够去除信号中无用的信息。并且,降噪还引出了一..._噪声很大的图片可以降噪吗

Effective Java 【对于所有对象都通用的方法】第13条 谨慎地覆盖clone_为继承设计类有两种选择,但无论选择其中的-程序员宅基地

文章浏览阅读152次。目录谨慎地覆盖cloneCloneable接口并没有包含任何方法,那么它到底有什么作用呢?Object类中的clone()方法如何重写好一个clone()方法1.对于数组类型我可以采用clone()方法的递归2.如果对象是非数组,建议提供拷贝构造器(copy constructor)或者拷贝工厂(copy factory)3.如果为线程安全的类重写clone()方法4.如果为需要被继承的类重写clone()方法总结谨慎地覆盖cloneCloneable接口地目的是作为对象的一个mixin接口(详见第20_为继承设计类有两种选择,但无论选择其中的

毕业设计 基于协同过滤的电影推荐系统-程序员宅基地

文章浏览阅读958次,点赞21次,收藏24次。今天学长向大家分享一个毕业设计项目基于协同过滤的电影推荐系统项目运行效果:项目获取:https://gitee.com/assistant-a/project-sharing21世纪是信息化时代,随着信息技术和网络技术的发展,信息化已经渗透到人们日常生活的各个方面,人们可以随时随地浏览到海量信息,但是这些大量信息千差万别,需要费事费力的筛选、甄别自己喜欢或者感兴趣的数据。对网络电影服务来说,需要用到优秀的协同过滤推荐功能去辅助整个系统。系统基于Python技术,使用UML建模,采用Django框架组合进行设

随便推点

你想要的10G SFP+光模块大全都在这里-程序员宅基地

文章浏览阅读614次。10G SFP+光模块被广泛应用于10G以太网中,在下一代移动网络、固定接入网、城域网、以及数据中心等领域非常常见。下面易天光通信(ETU-LINK)就为大家一一盘点下10G SFP+光模块都有哪些吧。一、10G SFP+双纤光模块10G SFP+双纤光模块是一种常规的光模块,有两个LC光纤接口,传输距离最远可达100公里,常用的10G SFP+双纤光模块有10G SFP+ SR、10G SFP+ LR,其中10G SFP+ SR的传输距离为300米,10G SFP+ LR的传输距离为10公里。_10g sfp+

计算机毕业设计Node.js+Vue基于Web美食网站设计(程序+源码+LW+部署)_基于vue美食网站源码-程序员宅基地

文章浏览阅读239次。该项目含有源码、文档、程序、数据库、配套开发软件、软件安装教程。欢迎交流项目运行环境配置:项目技术:Express框架 + Node.js+ Vue 等等组成,B/S模式 +Vscode管理+前后端分离等等。环境需要1.运行环境:最好是Nodejs最新版,我们在这个版本上开发的。其他版本理论上也可以。2.开发环境:Vscode或HbuilderX都可以。推荐HbuilderX;3.mysql环境:建议是用5.7版本均可4.硬件环境:windows 7/8/10 1G内存以上;_基于vue美食网站源码

oldwain随便写@hexun-程序员宅基地

文章浏览阅读62次。oldwain随便写@hexun链接:http://oldwain.blog.hexun.com/ ...

渗透测试-SQL注入-SQLMap工具_sqlmap拖库-程序员宅基地

文章浏览阅读843次,点赞16次,收藏22次。用这个工具扫描其它网站时,要注意法律问题,同时也比较慢,所以我们以之前写的登录页面为例子扫描。_sqlmap拖库

origin三图合一_神教程:Origin也能玩转图片拼接组合排版-程序员宅基地

文章浏览阅读1.5w次,点赞5次,收藏38次。Origin也能玩转图片的拼接组合排版谭编(华南师范大学学报编辑部,广州 510631)通常,我们利用Origin软件能非常快捷地绘制出一张单独的绘图。但是,我们在论文的撰写过程中,经常需要将多种科学实验图片(电镜图、示意图、曲线图等)组合在一张图片中。大多数人都是采用PPT、Adobe Illustrator、CorelDraw等软件对多种不同类型的图进行拼接的。那么,利用Origin软件能否实..._origin怎么把三个图做到一张图上

51单片机智能电风扇控制系统proteus仿真设计( 仿真+程序+原理图+报告+讲解视频)_电风扇模拟控制系统设计-程序员宅基地

文章浏览阅读4.2k次,点赞4次,收藏51次。51单片机智能电风扇控制系统仿真设计( proteus仿真+程序+原理图+报告+讲解视频)仿真图proteus7.8及以上 程序编译器:keil 4/keil 5 编程语言:C语言 设计编号:S0042。_电风扇模拟控制系统设计