Get the client's IP address

2019-02-09 08:55发布

问题:

Previously in other version of asp.net, I used these properties of HttpRequest:

Request.ServerVariables["REMOTE_ADDR"]
Request.UserHostAddress

How can I achieve the same in ASP.NET Core?

回答1:

You can use IHttpContextAccessor:

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

Now you get IP address this way"

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


回答2:

HttpContext.Connection.RemoteIpAddress is the property you are looking for



回答3:

And you can use Request

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