Тестирование разных IP-адресов локально - PullRequest
0 голосов
/ 22 сентября 2019

Я реализую некоторый код, в котором я использую IP-адрес посетителей, чтобы определить их местоположение.Для .net core 2 это:

var ipAddress = Request.HttpContext.Connection.RemoteIpAddress; 

Но, конечно, когда я тестирую локально, я всегда получаю адрес обратной связи ::1.Есть ли способ имитировать внешние IP-адреса при локальном тестировании?

Ответы [ 2 ]

1 голос
/ 22 сентября 2019

Вы можете создать сервис для получения удаленного адреса.Определите для него интерфейс, создайте 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());
    }
}
0 голосов
/ 23 сентября 2019

Для получения внешнего ip для localhost вам нужно отправить запрос на получение ip, и вы можете реализовать расширение для ConnectionInfo, например

public static class ConnectionExtension
{
    public static IPAddress RemotePublicIpAddress(this ConnectionInfo connection)
    {
        if (!IPAddress.IsLoopback(connection.RemoteIpAddress))
        {
            return connection.RemoteIpAddress;
        }
        else
        {
            string externalip = new WebClient().DownloadString("http://icanhazip.com").Replace("\n","");
            return IPAddress.Parse(externalip);
        }
    }
}

и использовать как

var ip = Request.HttpContext.Connection.RemotePublicIpAddress();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...