Get the client's IP address

2019-02-09 08:52发布

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?

3条回答
贼婆χ
2楼-- · 2019-02-09 09:21

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

查看更多
Bombasti
3楼-- · 2019-02-09 09:22

And you can use Request

var GetIp = Request.HttpContext.Connection.RemoteIpAddress.ToString();
查看更多
疯言疯语
4楼-- · 2019-02-09 09:23

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();
查看更多
登录 后发表回答