97 lines
2.8 KiB
C#
97 lines
2.8 KiB
C#
using System.Collections.Specialized;
|
|
using System.Net;
|
|
|
|
namespace YLErp.Web
|
|
{
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
public static class WebExtensions
|
|
{
|
|
/// <summary>
|
|
/// 是否本地请求
|
|
/// </summary>
|
|
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;
|
|
}
|
|
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
public static string UrlLeftPart(this HttpRequest request)
|
|
{
|
|
return $"{request.Scheme}://{request.Host}";
|
|
}
|
|
|
|
/// <summary>
|
|
/// IFormFile.SaveAs
|
|
/// </summary>
|
|
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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// IFormFile.ToUploadFileModel
|
|
/// </summary>
|
|
public static UploadFileModel ToUploadFileModel(this IFormFile file)
|
|
{
|
|
return new UploadFileModel
|
|
{
|
|
Length = file.Length,
|
|
FileName = file.FileName,
|
|
ContentType = file.ContentType,
|
|
OpenReadStream = file.OpenReadStream
|
|
};
|
|
}
|
|
|
|
/// <summary>
|
|
/// IFormFileCollection.ToUploadFileModel
|
|
/// </summary>
|
|
public static List<UploadFileModel> ToUploadFileModelList(this IFormFileCollection files)
|
|
{
|
|
return files.Select(ToUploadFileModel).ToList();
|
|
}
|
|
|
|
/// <summary>
|
|
/// IFormCollection.ToQueryString
|
|
/// </summary>
|
|
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);
|
|
}
|
|
}
|
|
}
|