-
-
Save jjxtra/3b240b31a1ed3ad783a7dcdb6df12c36 to your computer and use it in GitHub Desktop.
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using System.Net; | |
using System.Threading.Tasks; | |
using Microsoft.AspNetCore.Http; | |
namespace HttpContext_RemoteIPAddress | |
{ | |
public static class HttpContextExtensions | |
{ | |
/// <summary> | |
/// Get remote ip address, optionally allowing for x-forwarded-for header check | |
/// </summary> | |
/// <param name="context">Http context</param> | |
/// <param name="allowForwarded">Whether to allow x-forwarded-for header check</param> | |
/// <returns>IPAddress</returns> | |
public static IPAddress GetRemoteIPAddress(this HttpContext context, bool allowForwarded = true) | |
{ | |
if (allowForwarded) | |
{ | |
// if you are allowing these forward headers, please ensure you are restricting context.Connection.RemoteIpAddress | |
// to cloud flare ips: https://www.cloudflare.com/ips/ | |
string header = (context.Request.Headers["CF-Connecting-IP"].FirstOrDefault() ?? context.Request.Headers["X-Forwarded-For"].FirstOrDefault()); | |
if (IPAddress.TryParse(header, out IPAddress ip)) | |
{ | |
return ip; | |
} | |
} | |
return context.Connection.RemoteIpAddress; | |
} | |
} | |
} |
No funciona, devuelve
Ip Cliente: ::1 => _actionContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
Ip Acceso Servidor: ::1 =>_actionContextAccessor.HttpContext.Connection.LocalIpAddress.ToString();
Ip Acceso GetRemoteIp: ::1 => _actionContextAccessor.HttpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault();
No funciona, devuelve
Ip Cliente: ::1 => _actionContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();Ip Acceso Servidor: ::1 =>_actionContextAccessor.HttpContext.Connection.LocalIpAddress.ToString();
Ip Acceso GetRemoteIp: ::1 => _actionContextAccessor.HttpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault();
você está rodando localmente? "::1" é o valor padrão neste caso.
Thanks for the gist. You can use this to also parse ip addresses with port information.
if (IPEndPoint.TryParse(header, out IPEndPoint ip))
{
return ip.Address;
}
Thanks
Gostei