【问题标题】:Testing different IP addresses locally在本地测试不同的 IP 地址
【发布时间】:2019-09-22 16:37:18
【问题描述】:

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

var ipAddress = Request.HttpContext.Connection.RemoteIpAddress; 

当然,当我在本地测试时,我总是得到环回地址::1。有没有办法在本地测试时模拟外部 IP 地址?

【问题讨论】:

    标签: c# asp.net-core


    【解决方案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());
        }
    }
    

    【讨论】:

      【解决方案2】:

      要获取本地主机的外部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();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-24
        • 1970-01-01
        • 2021-01-03
        • 2013-07-02
        • 1970-01-01
        • 2011-09-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多