Search code examples
asp.net-coreip-address

Get the client's IP address


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?


Solution

  • 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();