9

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?

Set
  • 47,577
  • 22
  • 132
  • 150
Dalsier
  • 377
  • 3
  • 14

4 Answers4

12

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();
Maxime Rouiller
  • 13,614
  • 9
  • 57
  • 107
Sirwan Afifi
  • 10,654
  • 14
  • 63
  • 110
8

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

Maxime Rouiller
  • 13,614
  • 9
  • 57
  • 107
Joe Audette
  • 35,330
  • 11
  • 106
  • 99
0

And you can use Request

var GetIp = Request.HttpContext.Connection.RemoteIpAddress.ToString();
Mohammad Daliri
  • 1,370
  • 6
  • 20
  • 43
0

It works very well.

var ip = request.HttpContext.Connection.RemoteIpAddress;