获取客户端的IP地址
Get the client's IP address
之前在 asp.net 的其他版本中,我使用了 HttpRequest
的这些属性:
Request.ServerVariables["REMOTE_ADDR"]
Request.UserHostAddress
如何在 ASP.NET Core 中实现相同的目标?
HttpContext.Connection.RemoteIpAddress
就是您正在寻找的属性
您可以使用 IHttpContextAccessor
:
private IHttpContextAccessor _accessor;
public Foo(IHttpContextAccessor accessor)
{
_accessor = accessor;
}
现在您可以通过这种方式获得 IP 地址
var ip = _accessor.HttpContext.Connection.RemoteIpAddress.ToString();
你可以使用 Request
var GetIp = Request.HttpContext.Connection.RemoteIpAddress.ToString();
效果很好
var ip = request.HttpContext.Connection.RemoteIpAddress;
之前在 asp.net 的其他版本中,我使用了 HttpRequest
的这些属性:
Request.ServerVariables["REMOTE_ADDR"]
Request.UserHostAddress
如何在 ASP.NET Core 中实现相同的目标?
HttpContext.Connection.RemoteIpAddress
就是您正在寻找的属性
您可以使用 IHttpContextAccessor
:
private IHttpContextAccessor _accessor;
public Foo(IHttpContextAccessor accessor)
{
_accessor = accessor;
}
现在您可以通过这种方式获得 IP 地址
var ip = _accessor.HttpContext.Connection.RemoteIpAddress.ToString();
你可以使用 Request
var GetIp = Request.HttpContext.Connection.RemoteIpAddress.ToString();
效果很好
var ip = request.HttpContext.Connection.RemoteIpAddress;