#if NETCOREAPP3_1 using Microsoft.AspNetCore.Http; #else using System.Collections.Specialized; using System.Web; #endif using System; using System.IO; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace PaySharp.Core.Utils { /// /// Http工具类 /// public static class HttpUtil { #region 属性 #if NETCOREAPP3_1 private static IHttpContextAccessor _httpContextAccessor; /// /// 当前上下文 /// public static HttpContext Current => _httpContextAccessor.HttpContext; /// /// 本地IP /// public static string LocalIpAddress { get { try { var ipAddress = Current.Connection.LocalIpAddress; return IPAddress.IsLoopback(ipAddress) ? IPAddress.Loopback.ToString() : ipAddress.MapToIPv4().ToString(); } catch { return IPAddress.Loopback.ToString(); } } } /// /// 客户端IP /// public static string RemoteIpAddress { get { try { var ipAddress = Current.Connection.RemoteIpAddress; return IPAddress.IsLoopback(ipAddress) ? IPAddress.Loopback.ToString() : ipAddress.MapToIPv4().ToString(); } catch { return IPAddress.Loopback.ToString(); } } } /// /// 请求类型 /// public static string RequestType => Current.Request.Method; /// /// 表单 /// public static IFormCollection Form => Current.Request.Form; /// /// 请求体 /// public static Stream Body { get { var body = Current.Request.Body; try { if (body.CanSeek) { body.Position = 0; } } catch { } return body; } } #region 构造函数 /// /// 构造函数 /// static HttpUtil() { ServicePointManager.DefaultConnectionLimit = 200; } /// /// 配置 /// /// internal static void Configure(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; } #endregion #else public static HttpContext Current => HttpContext.Current; /// /// 本地IP /// public static string LocalIpAddress { get { try { var ip = Current.Request.UserHostAddress; var ipAddress = IPAddress.Parse(ip.Split(':')[0]); return IPAddress.IsLoopback(ipAddress) ? IPAddress.Loopback.ToString() : ipAddress.MapToIPv4().ToString(); } catch { return IPAddress.Loopback.ToString(); } } } /// /// 客户端IP /// public static string RemoteIpAddress { get { try { var ip = Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? Current.Request.ServerVariables["REMOTE_ADDR"]; var ipAddress = IPAddress.Parse(ip.Split(':')[0]); return IPAddress.IsLoopback(ipAddress) ? IPAddress.Loopback.ToString() : ipAddress.MapToIPv4().ToString(); } catch { return IPAddress.Loopback.ToString(); } } } /// /// 请求类型 /// public static string RequestType => Current.Request.HttpMethod; /// /// 表单 /// public static NameValueCollection Form => Current.Request.Form; /// /// 请求体 /// public static Stream Body { get { var inputStream = Current.Request.InputStream; try { if (inputStream.CanSeek) { inputStream.Position = 0; } } catch { } return inputStream; } } #endif /// /// 用户代理 /// public static string UserAgent => Current.Request.Headers["User-Agent"]; /// /// 内容类型 /// public static string ContentType => Current.Request.ContentType; /// /// 参数 /// public static string QueryString => Current.Request.QueryString.ToString(); #endregion #region 方法 /// /// 跳转到指定链接 /// /// 链接 public static void Redirect(string url) { Current.Response.Redirect(url); } /// /// 输出内容 /// /// 内容 public static void Write(string text) { Current.Response.ContentType = "text/plain;charset=utf-8"; #if NETCOREAPP3_1 Task.Run(async () => { await Current.Response.WriteAsync(text); }) .GetAwaiter() .GetResult(); #else Current.Response.Write(text); Current.Response.End(); #endif } /// /// 输出文件 /// /// 文件流 public static void Write(FileStream stream) { var size = stream.Length; var buffer = new byte[size]; stream.Read(buffer, 0, (int)size); stream.Dispose(); File.Delete(stream.Name); Current.Response.ContentType = "application/octet-stream"; Current.Response.Headers.Add("Content-Disposition", "attachment;filename=" + WebUtility.UrlEncode(Path.GetFileName(stream.Name))); Current.Response.Headers.Add("Content-Length", size.ToString()); #if NETCOREAPP3_1 Task.Run(async () => { await Current.Response.Body.WriteAsync(buffer, 0, (int)size); }) .GetAwaiter() .GetResult(); Current.Response.Body.Close(); #else Current.Response.BinaryWrite(buffer); Current.Response.End(); Current.Response.Close(); #endif } /// /// Get请求 /// /// url /// public static string Get(string url) { var request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.ContentType = "application/x-www-form-urlencoded;charset=utf-8"; using var response = request.GetResponse(); using var reader = new StreamReader(response.GetResponseStream()); return reader.ReadToEnd().Trim(); } /// /// 异步Post请求 /// /// url /// public static async Task GetAsync(string url) { return await Task.Run(() => Get(url)); } /// /// Post请求 /// /// url /// 数据 /// 证书 /// public static string Post(string url, string data, X509Certificate2 cert = null) { if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); } var dataByte = Encoding.UTF8.GetBytes(data); var request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded;charset=utf-8"; request.ContentLength = dataByte.Length; request.UserAgent = "PaySharp"; if (cert != null) { request.ClientCertificates.Add(cert); } using (var outStream = request.GetRequestStream()) { outStream.Write(dataByte, 0, dataByte.Length); } using var response = (HttpWebResponse)request.GetResponse(); using var reader = new StreamReader(response.GetResponseStream()); return reader.ReadToEnd().Trim(); } private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; } /// /// 下载 /// /// url /// public static byte[] Download(string url) { using var webClient = new WebClient(); return webClient.DownloadData(url); } /// /// 异步下载 /// /// url /// public static async Task DownloadAsync(string url) { using var webClient = new WebClient(); return await webClient.DownloadDataTaskAsync(url); } #endregion } }