Reputation: 107
I get server IP Address instead of client IP by using below method in ASP.NET CORE Web API .
Please tell me where I'm going wrong. I have used ServerVariables["HTTP_X_FORWARDED_FOR"]
in asp mvc before and that has worked correctly.
private string DetectIPAddress(HttpRequest request)
{
var _IP = "RemoteIp:" + request.HttpContext.Connection.RemoteIpAddress.ToString() + " - LocalIpAddress:" +
request.HttpContext.Connection.LocalIpAddress;
try
{
_IP += " IP.AddressFamily:" + Dns.GetHostEntry(Dns.GetHostName()).AddressList[1].ToString();
_IP += " HostName:" + Dns.GetHostEntry(Dns.GetHostName()).HostName;
}
catch (Exception e)
{
}
return _IP;
}
Upvotes: 5
Views: 11652
Reputation: 191
I using this method to get IP in .net core 3.1
public static string GetIPAddress(HttpContext context)
{
if (!string.IsNullOrEmpty(context.Request.Headers["X-Forwarded-For"]))
{
return context.Request.Headers["X-Forwarded-For"];
}
return context.Connection?.RemoteIpAddress?.ToString();
}
In Startup.cs add this code
app.UseForwardedHeaders(new ForwardedHeadersOptions() { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.All });
Upvotes: 1
Reputation: 9596
Use this line in your action method :
string ipAddress = HttpContext.Connection.RemoteIpAddress?.ToString();
Upvotes: 0
Reputation: 8588
Getting the client IP sounds easy but in fact I've tried to get the client IP for many hours until I found this gist extension method in @Voodoo's comment that helped me. I want to make it more prominent and therefore create a separate answer. It works with .NET 5 on AWS fargate likely with some kind of load balancer pass-through where RemoteIpAddress alone does not work.
public static class HttpContextExtensions
{
//https://gist.github.com/jjxtra/3b240b31a1ed3ad783a7dcdb6df12c36
public static IPAddress GetRemoteIPAddress(this HttpContext context, bool allowForwarded = true)
{
if (allowForwarded)
{
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;
}
}
Use it like this:
var ip = HttpContext.GetRemoteIPAddress().ToString();
Upvotes: 6
Reputation: 1658
In Asp.Net Core Web API
to get Remote Client, IP Address is changed to the previous version of Asp.Net
Asp.Net Core
introduced a new library for Http request and response.
Require the following namespace to add.
using Microsoft.AspNetCore.Http.Features;
Once, you added namespace
then just need to add following a line of code for capture the Remote Client IP Address.
HttpContext.Features.Get()?.RemoteIpAddress?.ToString();
Note: When you try to run the application from the local system so above line of code return the result "::1" but it will work once you deploy your application somewhere
Upvotes: 0