在本地测试不同的IP地址

时间:2019-09-22 16:37:18

标签: c# asp.net-core

我正在实现一些代码,在这些代码中,我使用访问者的IP地址来确定他们的位置。对于.net core 2,这是:

var ipAddress = Request.HttpContext.Connection.RemoteIpAddress; 

但是,当然,当我在本地测试时,我总是得到回送地址::1。在本地测试时,有没有一种模拟外部IP地址的方法?

2 个答案:

答案 0 :(得分:1)

您可以创建用于检索远程地址的服务。为它定义一个接口并创建2个实现并将其注入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");
    }
}

启动

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());
    }
}

答案 1 :(得分:0)

要获取本地主机的外部ip,您需要发送请求以检索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();