Coder Perfect

How do I get client IP address in ASP.NET CORE?

Problem

Can you please let me know how to get client IP address in ASP.NET when using MVC 6. Request.ServerVariables[“REMOTE_ADDR”] does not work.

Asked by eadam

Solution #1

The API is now up to date. I’m not sure when it changed, but you may now do this, according to Damien Edwards in late December:

var remoteIpAddress = request.HttpContext.Connection.RemoteIpAddress;

Answered by David Peden

Solution #2

Add a dependency to project.json.

"Microsoft.AspNetCore.HttpOverrides": "2.2.0"

Add the following to the Configure() method in Startup.cs:

app.UseForwardedHeaders(new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor |
    ForwardedHeaders.XForwardedProto
});  

And, of course:

using Microsoft.AspNetCore.HttpOverrides;

Then I could acquire the IP address by typing in:

Request.HttpContext.Connection.RemoteIpAddress

When debugging in Visual Studio, I always got IPV6 localhost, however when placed on an IIS, I always got the remote IP.

Here are some important links: In ASP.NET CORE, how can I acquire the client’s IP address? RemoteIpAddress is never null.

It’s possible that the::1 is due to:

Edit 12/2020: Thanks to SolidSnake, the most recent version is 2.2.0 as of December 2020.

06/2021 Update: Hakan Fstk is to be thanked for the following: Microsoft.AspNetCore.Builder is the namespace in.NET 5.

Answered by Johna

Solution #3

To manage the presence of a Load Balancer, some fallback logic can be provided.

Also, even without a Load Balancer, the X-Forwarded-For header appears to be set (perhaps due of the additional Kestrel layer?):

public string GetRequestIP(bool tryUseXForwardHeader = true)
{
    string ip = null;

    // todo support new "Forwarded" header (2014) https://en.wikipedia.org/wiki/X-Forwarded-For

    // X-Forwarded-For (csv list):  Using the First entry in the list seems to work
    // for 99% of cases however it has been suggested that a better (although tedious)
    // approach might be to read each IP from right to left and use the first public IP.
    // http://stackoverflow.com/a/43554000/538763
    //
    if (tryUseXForwardHeader)
        ip = GetHeaderValueAs<string>("X-Forwarded-For").SplitCsv().FirstOrDefault();

    // RemoteIpAddress is always null in DNX RC1 Update1 (bug).
    if (ip.IsNullOrWhitespace() && _httpContextAccessor.HttpContext?.Connection?.RemoteIpAddress != null)
        ip = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();

    if (ip.IsNullOrWhitespace())
        ip = GetHeaderValueAs<string>("REMOTE_ADDR");

    // _httpContextAccessor.HttpContext?.Request?.Host this is the local host.

    if (ip.IsNullOrWhitespace())
        throw new Exception("Unable to determine caller's IP.");

    return ip;
}

public T GetHeaderValueAs<T>(string headerName)
{
    StringValues values;

    if (_httpContextAccessor.HttpContext?.Request?.Headers?.TryGetValue(headerName, out values) ?? false)
    {
        string rawValues = values.ToString();   // writes out as Csv when there are multiple.

        if (!rawValues.IsNullOrWhitespace())
            return (T)Convert.ChangeType(values.ToString(), typeof(T));
    }
    return default(T);
}

public static List<string> SplitCsv(this string csvList, bool nullOrWhitespaceInputReturnsNull = false)
{
    if (string.IsNullOrWhiteSpace(csvList))
        return nullOrWhitespaceInputReturnsNull ? null : new List<string>();

    return csvList
        .TrimEnd(',')
        .Split(',')
        .AsEnumerable<string>()
        .Select(s => s.Trim())
        .ToList();
}

public static bool IsNullOrWhitespace(this string s)
{
    return String.IsNullOrWhiteSpace(s);
}

Assumes that DI provided _httpContextAccessor.

Answered by crokusek

Solution #4

You can access this information by using the IHttpConnectionFeature.

var remoteIpAddress = httpContext.GetFeature<IHttpConnectionFeature>()?.RemoteIpAddress;

Answered by Kiran

Solution #5

var remoteIpAddress = HttpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress;

Answered by feradz

Post is based on https://stackoverflow.com/questions/28664686/how-do-i-get-client-ip-address-in-asp-net-core