如何解决ASP .NET Core:获取用户 IP 地址
我有一张桌子:有模型
public class ArticleLike:BaseEntity
{
public long? UserId { get; set; }
public string UserIp { get; set; }
public ICollection<User> User { get; set; }
}
如何获取用户的IP地址? 我必须在服务或存储库上编写它的方法吗?
解决方法
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地址
var remoteIpAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString();
可以通过 HttpContext.Connection 对象检索客户端 IP 地址。
属性 RemoteIpAddress 是客户端 IP 地址。返回的对象(System.Net.IpAddress)可用于检查是IPV4还是IPV6地址。
例如,如果您得到类似 ::1 的结果,则这是 IPv6 格式
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。