You can create a service for retrieving remote address. Define an interface for it and create 2 implementations and inject them depending on the current environment
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"); } }
Startup
if (HostingEnvironment.IsProduction()) { services.AddScoped<IRemoteIpService, RemoteIpService>(); } else { services.AddScoped<IRemoteIpService, DummyRemoteIpService>(); }
Usage
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()); } }