Files
juipnet/Infrastructure/Hncore.Infrastructure/WebApi/WebRequest.cs
“wanyongkang” 40a40b6d36 忽略
2020-12-28 14:55:48 +08:00

71 lines
2.0 KiB
C#

using Microsoft.AspNetCore.Http;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Hncore.Infrastructure.Core.Web
{
public static class HttpContextExtension
{
public static string GetUserIp(this HttpContext context)
{
var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
if (string.IsNullOrEmpty(ip))
{
ip = context.Connection.RemoteIpAddress.ToString();
}
return ip;
}
public static string GetAbsoluteUri(this HttpRequest request)
{
return new StringBuilder()
.Append(request.Scheme)
.Append("://")
.Append(request.Host)
.Append(request.PathBase)
.Append(request.Path)
.Append(request.QueryString)
.ToString();
}
public static async Task<string> ReadBodyAsStringAsync(this HttpRequest request)
{
request.EnableBuffering();
var requestReader = new StreamReader(request.Body);
var requestBody = await requestReader.ReadToEndAsync();
request.Body.Position = 0;
return requestBody;
}
}
public static class IsLocalExtension
{
private const string NullIpAddress = "::1";
public static bool IsLocal(this HttpRequest req)
{
var connection = req.HttpContext.Connection;
if (connection.RemoteIpAddress.IsSet())
{
return connection.LocalIpAddress.IsSet()
? connection.RemoteIpAddress.Equals(connection.LocalIpAddress)
: IPAddress.IsLoopback(connection.RemoteIpAddress);
}
return true;
}
private static bool IsSet(this IPAddress address)
{
return address != null && address.ToString() != NullIpAddress;
}
}
}