Actually I have a class called BaseRequest which has a variable called ClientIP, currently the front developer should set this variable, but I want this variable not in the class and after calling the web service I get the user's IP address, is it This can, because the code below gives me the IP address of the server, but I want to get the IP address of the user who called the web service.
BaseRequest:
namespace Api.Models.Controllers
{
public class BaseRequest
{
public string AppId { get; set; }
public string ClientIP { get; set; } //I want to remove this variable and get the user's IP address directly
}
}
Utility:
public static string GetClientIp()
{
try
{
string strHostName = System.Net.Dns.GetHostName();
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList
.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork);
return ipAddress?.ToString();
}
catch (Exception ex)
{
return "10.0.0.0";
}
//return HttpContext.Current.Connection.RemoteIpAddress?.ToString() ?? "10.0.0.0";
}
That is, the AppId variable should be in the BaseRequest class and the ClientIP variable should be removed, and when the web service is called, it can get the user's IP address with the above function and store it in the database, because in this method, the front-end programmer may Set ClientIP to blank or set a fake or fixed IP.
System.Net.Dns.GetHostName()tries to get the host name of the server where the code is running. a little research on internet suggest to read this and this