【问题标题】:Get the client's IP address获取客户端的IP地址
【发布时间】:2019-05-10 23:54:56
【问题描述】:

之前在其他版本的asp.net中,我使用了HttpRequest的这些属性:

Request.ServerVariables["REMOTE_ADDR"]
Request.UserHostAddress

如何在 ASP.NET Core 中实现相同的功能?

【问题讨论】:

    标签: asp.net-core ip-address


    【解决方案1】:

    你可以使用IHttpContextAccessor:

    private IHttpContextAccessor _accessor;
    public Foo(IHttpContextAccessor accessor)
    {
        _accessor = accessor;
    }
    

    现在你通过这种方式获得 IP 地址”

    var ip = _accessor.HttpContext.Connection.RemoteIpAddress.ToString();
    

    【讨论】:

    • 我无法在 DNX (full clr) 上完成这项工作,有什么建议吗? RemoteIpAddress 属性在我的应用程序中为空...
    • @MarcinZablocki 你必须在 Startup 中注册它:services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    【解决方案2】:

    HttpContext.Connection.RemoteIpAddress 是您要查找的属性

    【讨论】:

      【解决方案3】:

      你可以使用请求

      var GetIp = Request.HttpContext.Connection.RemoteIpAddress.ToString();
      

      【讨论】:

        【解决方案4】:

        效果很好。

        var ip = request.HttpContext.Connection.RemoteIpAddress;
        

        【讨论】:

          猜你喜欢
          • 2019-01-14
          • 2019-11-13
          • 2013-07-07
          • 2011-05-26
          • 2015-03-01
          • 2011-01-08
          • 2014-12-29
          • 2012-03-14
          • 2016-01-26
          相关资源
          最近更新 更多