【问题标题】:ASP .NET Core: Get User IP AddressASP .NET Core:获取用户 IP 地址
【发布时间】:2021-09-03 18:48:07
【问题描述】:

我有一张桌子:有一个模型

public class ArticleLike:BaseEntity
{
    public long? UserId { get; set; }
    public string UserIp { get; set; }
    public ICollection<User> User { get; set; }
}

如何获取用户的IP地址? 我必须在服务或存储库上编写它的方法吗?

【问题讨论】:

    标签: database asp.net-core get ip ip-address


    【解决方案1】:

    获取客户端用户IP地址

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

    客户端IP地址可以通过HttpContext.Connection对象获取。

    属性 RemoteIpAddress 是客户端 IP 地址。返回的对象(System.Net.IpAddress)可以用来判断是IPV4还是IPV6地址。

    例如,如果您得到类似 ::1 的结果,这就是 IPv6 格式

    【讨论】:

      【解决方案2】:
      var remoteIpAddress = Request.HttpContext.Connection.RemoteIpAddress;
      

      var remoteIpAddress = httpContext.GetFeature<IHttpConnectionFeature>()?.RemoteIpAddress;
      

      简单用法:

      在控制器中

      public class HomeController : Controller
      {
      private readonly IHttpContextAccessor _httpContextAccessor;
      
      public HomeController(IHttpContextAccessor httpContextAccessor)
      {
          _httpContextAccessor = httpContextAccessor;
      }
      
      public IActionResult Index()
      {
          var ip = _httpContextAccessor.HttpContext?.Connection?.RemoteIpAddress?.ToString();
          return Content(ip);
      }
      

      }

      在启动文件中:

      public void ConfigureServices(IServiceCollection services)
      {
         services.AddHttpContextAccessor();
      }    
      

      【讨论】:

      • 我使用这种方法,但我得到这样的 IP :fe80::18a3:6c10:468f:f212%16 我不能从你的代码中使用,因为我有错误:'type' does not contain a HttpContext 上“标识符”的定义
      • 我终于可以获取IP地址并将其添加到数据库中了。但是现在我想在单击心脏时显示在视图上,然后更改其颜色并添加其喜欢的数量。如果视图上的条件代码,我的写作能力真的很弱。 :(
      猜你喜欢
      • 2014-04-27
      • 2022-01-20
      • 1970-01-01
      • 2014-09-27
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 2022-01-22
      • 2011-02-06
      相关资源
      最近更新 更多