CSharp-Single-EFCore/Bunny.Common/Utils/Net/Request.cs

32 lines
1.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Net;
using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Tokens;
namespace Bunny.Common.Utils.Net;
public static partial class NetUtil
{
/// <summary>
/// 获取请求的IP地址
/// </summary>
/// <param name="context">HttpContext 上下问对象</param>
/// <param name="getIpv4AddressType">是否获取IPv4地址默认为IPv4</param>
/// <returns>IP地址</returns>
public static string GetRequestIpAddress(HttpContext context, bool getIpv4AddressType = true)
{
// 获取IP地址
var ipAddress = context.Connection.RemoteIpAddress!.ToString();
// 转换IP地址格式
var ip = IPAddress.Parse(ipAddress);
// 转换成IPv4
var toIPv4 = ip.MapToIPv4().ToString();
// 转换成IPv6
var toIPv6 = ip.MapToIPv6().ToString();
// 如果获取IPv4地址
ipAddress = getIpv4AddressType ? toIPv4 : toIPv6;
// 如果有IP直接返回
return ipAddress.IsNullOrEmpty() ? "" : ipAddress;
}
}