using System.Collections.Specialized; using System.Net; namespace YLErp.Web { /// /// /// public static class WebExtensions { /// /// 是否本地请求 /// public static bool IsLocal(this HttpRequest req) { var connection = req.HttpContext.Connection; if (connection.RemoteIpAddress != null) { if (connection.LocalIpAddress != null) { return connection.RemoteIpAddress.Equals(connection.LocalIpAddress); } else { return IPAddress.IsLoopback(connection.RemoteIpAddress); } } // for in memory TestServer or when dealing with default connection info return connection.RemoteIpAddress == null && connection.LocalIpAddress == null; } /// /// /// public static string UrlLeftPart(this HttpRequest request) { return $"{request.Scheme}://{request.Host}"; } /// /// IFormFile.SaveAs /// public static void SaveAs(this IFormFile file, string filePath) { Directory.CreateDirectory(Path.GetDirectoryName(filePath)); using var stream = file.OpenReadStream(); using var fstream = File.OpenWrite(filePath); stream.CopyTo(fstream); } /// /// IFormFile.ToUploadFileModel /// public static UploadFileModel ToUploadFileModel(this IFormFile file) { return new UploadFileModel { Length = file.Length, FileName = file.FileName, ContentType = file.ContentType, OpenReadStream = file.OpenReadStream }; } /// /// IFormFileCollection.ToUploadFileModel /// public static List ToUploadFileModelList(this IFormFileCollection files) { return files.Select(ToUploadFileModel).ToList(); } /// /// IFormCollection.ToQueryString /// public static string ToQueryString(IFormCollection form, bool urlencoded = false) { var nv = new NameValueCollection(); foreach (var key in form.Keys) { if (form.TryGetValue(key, out var values)) { foreach (var value in values) { nv.Add(key, value); } } } return YieldChain.Helpers.UrlHelper.ToQueryString(nv, urlencoded); } } }