HttpUtil.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. #if NETCOREAPP3_1
  2. using Microsoft.AspNetCore.Http;
  3. #else
  4. using System.Collections.Specialized;
  5. using System.Web;
  6. #endif
  7. using System;
  8. using System.IO;
  9. using System.Net;
  10. using System.Net.Security;
  11. using System.Security.Cryptography.X509Certificates;
  12. using System.Text;
  13. using System.Threading.Tasks;
  14. namespace PaySharp.Core.Utils
  15. {
  16. /// <summary>
  17. /// Http工具类
  18. /// </summary>
  19. public static class HttpUtil
  20. {
  21. #region 属性
  22. #if NETCOREAPP3_1
  23. private static IHttpContextAccessor _httpContextAccessor;
  24. /// <summary>
  25. /// 当前上下文
  26. /// </summary>
  27. public static HttpContext Current => _httpContextAccessor.HttpContext;
  28. /// <summary>
  29. /// 本地IP
  30. /// </summary>
  31. public static string LocalIpAddress
  32. {
  33. get
  34. {
  35. try
  36. {
  37. var ipAddress = Current.Connection.LocalIpAddress;
  38. return IPAddress.IsLoopback(ipAddress) ?
  39. IPAddress.Loopback.ToString() :
  40. ipAddress.MapToIPv4().ToString();
  41. }
  42. catch
  43. {
  44. return IPAddress.Loopback.ToString();
  45. }
  46. }
  47. }
  48. /// <summary>
  49. /// 客户端IP
  50. /// </summary>
  51. public static string RemoteIpAddress
  52. {
  53. get
  54. {
  55. try
  56. {
  57. var ipAddress = Current.Connection.RemoteIpAddress;
  58. return IPAddress.IsLoopback(ipAddress) ?
  59. IPAddress.Loopback.ToString() :
  60. ipAddress.MapToIPv4().ToString();
  61. }
  62. catch
  63. {
  64. return IPAddress.Loopback.ToString();
  65. }
  66. }
  67. }
  68. /// <summary>
  69. /// 请求类型
  70. /// </summary>
  71. public static string RequestType => Current.Request.Method;
  72. /// <summary>
  73. /// 表单
  74. /// </summary>
  75. public static IFormCollection Form => Current.Request.Form;
  76. /// <summary>
  77. /// 请求体
  78. /// </summary>
  79. public static Stream Body
  80. {
  81. get
  82. {
  83. var body = Current.Request.Body;
  84. try
  85. {
  86. if (body.CanSeek)
  87. {
  88. body.Position = 0;
  89. }
  90. }
  91. catch
  92. { }
  93. return body;
  94. }
  95. }
  96. #region 构造函数
  97. /// <summary>
  98. /// 构造函数
  99. /// </summary>
  100. static HttpUtil()
  101. {
  102. ServicePointManager.DefaultConnectionLimit = 200;
  103. }
  104. /// <summary>
  105. /// 配置
  106. /// </summary>
  107. /// <param name="httpContextAccessor"></param>
  108. internal static void Configure(IHttpContextAccessor httpContextAccessor)
  109. {
  110. _httpContextAccessor = httpContextAccessor;
  111. }
  112. #endregion
  113. #else
  114. public static HttpContext Current => HttpContext.Current;
  115. /// <summary>
  116. /// 本地IP
  117. /// </summary>
  118. public static string LocalIpAddress
  119. {
  120. get
  121. {
  122. try
  123. {
  124. var ip = Current.Request.UserHostAddress;
  125. var ipAddress = IPAddress.Parse(ip.Split(':')[0]);
  126. return IPAddress.IsLoopback(ipAddress) ?
  127. IPAddress.Loopback.ToString() :
  128. ipAddress.MapToIPv4().ToString();
  129. }
  130. catch
  131. {
  132. return IPAddress.Loopback.ToString();
  133. }
  134. }
  135. }
  136. /// <summary>
  137. /// 客户端IP
  138. /// </summary>
  139. public static string RemoteIpAddress
  140. {
  141. get
  142. {
  143. try
  144. {
  145. var ip = Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ??
  146. Current.Request.ServerVariables["REMOTE_ADDR"];
  147. var ipAddress = IPAddress.Parse(ip.Split(':')[0]);
  148. return IPAddress.IsLoopback(ipAddress) ?
  149. IPAddress.Loopback.ToString() :
  150. ipAddress.MapToIPv4().ToString();
  151. }
  152. catch
  153. {
  154. return IPAddress.Loopback.ToString();
  155. }
  156. }
  157. }
  158. /// <summary>
  159. /// 请求类型
  160. /// </summary>
  161. public static string RequestType => Current.Request.HttpMethod;
  162. /// <summary>
  163. /// 表单
  164. /// </summary>
  165. public static NameValueCollection Form => Current.Request.Form;
  166. /// <summary>
  167. /// 请求体
  168. /// </summary>
  169. public static Stream Body
  170. {
  171. get
  172. {
  173. var inputStream = Current.Request.InputStream;
  174. try
  175. {
  176. if (inputStream.CanSeek)
  177. {
  178. inputStream.Position = 0;
  179. }
  180. }
  181. catch { }
  182. return inputStream;
  183. }
  184. }
  185. #endif
  186. /// <summary>
  187. /// 用户代理
  188. /// </summary>
  189. public static string UserAgent => Current.Request.Headers["User-Agent"];
  190. /// <summary>
  191. /// 内容类型
  192. /// </summary>
  193. public static string ContentType => Current.Request.ContentType;
  194. /// <summary>
  195. /// 参数
  196. /// </summary>
  197. public static string QueryString => Current.Request.QueryString.ToString();
  198. #endregion
  199. #region 方法
  200. /// <summary>
  201. /// 跳转到指定链接
  202. /// </summary>
  203. /// <param name="url">链接</param>
  204. public static void Redirect(string url)
  205. {
  206. Current.Response.Redirect(url);
  207. }
  208. /// <summary>
  209. /// 输出内容
  210. /// </summary>
  211. /// <param name="text">内容</param>
  212. public static void Write(string text)
  213. {
  214. Current.Response.ContentType = "text/plain;charset=utf-8";
  215. #if NETCOREAPP3_1
  216. Task.Run(async () =>
  217. {
  218. await Current.Response.WriteAsync(text);
  219. })
  220. .GetAwaiter()
  221. .GetResult();
  222. #else
  223. Current.Response.Write(text);
  224. Current.Response.End();
  225. #endif
  226. }
  227. /// <summary>
  228. /// 输出文件
  229. /// </summary>
  230. /// <param name="stream">文件流</param>
  231. public static void Write(FileStream stream)
  232. {
  233. var size = stream.Length;
  234. var buffer = new byte[size];
  235. stream.Read(buffer, 0, (int)size);
  236. stream.Dispose();
  237. File.Delete(stream.Name);
  238. Current.Response.ContentType = "application/octet-stream";
  239. Current.Response.Headers.Add("Content-Disposition", "attachment;filename=" + WebUtility.UrlEncode(Path.GetFileName(stream.Name)));
  240. Current.Response.Headers.Add("Content-Length", size.ToString());
  241. #if NETCOREAPP3_1
  242. Task.Run(async () =>
  243. {
  244. await Current.Response.Body.WriteAsync(buffer, 0, (int)size);
  245. })
  246. .GetAwaiter()
  247. .GetResult();
  248. Current.Response.Body.Close();
  249. #else
  250. Current.Response.BinaryWrite(buffer);
  251. Current.Response.End();
  252. Current.Response.Close();
  253. #endif
  254. }
  255. /// <summary>
  256. /// Get请求
  257. /// </summary>
  258. /// <param name="url">url</param>
  259. /// <returns></returns>
  260. public static string Get(string url)
  261. {
  262. var request = (HttpWebRequest)WebRequest.Create(url);
  263. request.Method = "GET";
  264. request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
  265. using var response = request.GetResponse();
  266. using var reader = new StreamReader(response.GetResponseStream());
  267. return reader.ReadToEnd().Trim();
  268. }
  269. /// <summary>
  270. /// 异步Post请求
  271. /// </summary>
  272. /// <param name="url">url</param>
  273. /// <returns></returns>
  274. public static async Task<string> GetAsync(string url)
  275. {
  276. return await Task.Run(() => Get(url));
  277. }
  278. /// <summary>
  279. /// Post请求
  280. /// </summary>
  281. /// <param name="url">url</param>
  282. /// <param name="data">数据</param>
  283. /// <param name="cert">证书</param>
  284. /// <returns></returns>
  285. public static string Post(string url, string data, X509Certificate2 cert = null)
  286. {
  287. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  288. {
  289. ServicePointManager.ServerCertificateValidationCallback =
  290. new RemoteCertificateValidationCallback(CheckValidationResult);
  291. }
  292. var dataByte = Encoding.UTF8.GetBytes(data);
  293. var request = (HttpWebRequest)WebRequest.Create(url);
  294. request.Method = "POST";
  295. request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
  296. request.ContentLength = dataByte.Length;
  297. request.UserAgent = "PaySharp";
  298. if (cert != null)
  299. {
  300. request.ClientCertificates.Add(cert);
  301. }
  302. using (var outStream = request.GetRequestStream())
  303. {
  304. outStream.Write(dataByte, 0, dataByte.Length);
  305. }
  306. using var response = (HttpWebResponse)request.GetResponse();
  307. using var reader = new StreamReader(response.GetResponseStream());
  308. return reader.ReadToEnd().Trim();
  309. }
  310. private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  311. {
  312. return true;
  313. }
  314. /// <summary>
  315. /// 下载
  316. /// </summary>
  317. /// <param name="url">url</param>
  318. /// <returns></returns>
  319. public static byte[] Download(string url)
  320. {
  321. using var webClient = new WebClient();
  322. return webClient.DownloadData(url);
  323. }
  324. /// <summary>
  325. /// 异步下载
  326. /// </summary>
  327. /// <param name="url">url</param>
  328. /// <returns></returns>
  329. public static async Task<byte[]> DownloadAsync(string url)
  330. {
  331. using var webClient = new WebClient();
  332. return await webClient.DownloadDataTaskAsync(url);
  333. }
  334. #endregion
  335. }
  336. }