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

ID : 10382

viewed : 31

Tags : c#asp.net-coreasp.net-core-mvcc#

Top 5 Answer for c# - How do I get client IP address in ASP.NET CORE?

vote vote


The API has been updated. Not sure when it changed but according to Damien Edwards in late December, you can now do this:

var remoteIpAddress = request.HttpContext.Connection.RemoteIpAddress; 
vote vote


In project.json add a dependency to:

"Microsoft.AspNetCore.HttpOverrides": "2.2.0" 

In Startup.cs, in the Configure() method add:

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

And, of course:

using Microsoft.AspNetCore.HttpOverrides; 

Then, I could get the ip by using:


In my case, when debugging in VS I got always IpV6 localhost, but when deployed on an IIS I got always the remote IP.

Some useful links: How do I get client IP address in ASP.NET CORE? and RemoteIpAddress is always null

The ::1 is maybe because of:

Connections termination at IIS, which then forwards to Kestrel, the v.next web server, so connections to the web server are indeed from localhost. (https://stackoverflow.com/a/35442401/5326387)

Edit 12/2020: Thanks to SolidSnake: as of Dec 2020 the latest version is 2.2.0

Edit 06/2021: Thanks to Hakan Fıstık: In .NET 5 the namespace is Microsoft.AspNetCore.Builder

vote vote


Some fallback logic can be added to handle the presence of a Load Balancer.

Also, through inspection, the X-Forwarded-For header happens to be set anyway even without a Load Balancer (possibly because of 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 _httpContextAccessor was provided through DI.

vote vote


You can use the IHttpConnectionFeature for getting this information.

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


In ASP.NET 2.1, In StartUp.cs Add This Services:

services.AddHttpContextAccessor(); services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>(); 

and then do 3 step:

  1. Define a variable in your MVC controller

    private IHttpContextAccessor _accessor; 
  2. DI into the controller's constructor

    public SomeController(IHttpContextAccessor accessor) {     _accessor = accessor; } 
  3. Retrieve the IP Address


This is how it is done.

Top 3 video Explaining c# - How do I get client IP address in ASP.NET CORE?