Вы можете создать сервис для получения удаленного адреса.Определите для него интерфейс, создайте 2 реализации и внедрите их в зависимости от текущей среды
public interface IRemoteIpService
{
IPAddress GetRemoteIpAddress();
}
public class RemoteIpService : IRemoteIpService
{
private readonly IHttpContextAccessor _httpContextAccessor;
public RemoteIpService(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public IPAddress GetRemoteIpAddress()
{
return _httpContextAccessor.HttpContext.Connection.RemoteIpAddress;
}
}
public class DummyRemoteIpService : IRemoteIpService
{
public IPAddress GetRemoteIpAddress()
{
//add your implementation
return IPAddress.Parse("120.1.1.99");
}
}
Запуск
if (HostingEnvironment.IsProduction())
{
services.AddScoped<IRemoteIpService, RemoteIpService>();
}
else
{
services.AddScoped<IRemoteIpService, DummyRemoteIpService>();
}
Использование
public class TestController : Controller
{
//...
private readonly IRemoteIpService _remoteIpService;
public TestController(IRemoteIpService remoteIpService)
{
//...
_remoteIpService = remoteIpService;
}
//..
[HttpGet]
public IActionResult Test()
{
var ip = _remoteIpService.GetRemoteIpAddress();
return Json(ip.ToString());
}
}