Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Client IP in .net core 6 web api

How can we get Client IP in .net core 6 web api. I have already implemented this in .net core 3, and 4 and never faced the problem, For some reason the code is not working in .net core 6, Instead of client IP, the code is giving Server IP. I have hosted this on an IIS.

Below is the code from program.cs

var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});

//rest of the code follows

var app = builder.Build();
app.UseForwardedHeaders();

//rest of the code follows

Below is the code from the controller

string ip_address = Request.HttpContext.Connection.RemoteIpAddress?.ToString()

The above line is always giving me the IP address of the server where this web api is deployed, instead I need to IP address of the client from where the request has come.

Please let me know what is wrong here.

================================================================ Based on the early responses I received, Adding more information my question, My Web API is hosted behind a company firewall and the API is accessed from several networks outside of the company.

like image 421
VIRIYALA NARESH Avatar asked Feb 02 '26 21:02

VIRIYALA NARESH


1 Answers

I am able to get the IP address from WebAPI controller this way:

 [HttpGet("api/GetIP")]
public async Task<IActionResult> GetIP()
{
    string ip = this.HttpContext.GetServerVariable("REMOTE_HOST");
    if (ip == null)
       {
          ip = this.HttpContext.GetServerVariable("REMOTE_ADDR");
       }
    return Ok($"IPAddress: {ip}");
}

I tested this on IIS and Azure, and it is in .net 6

I noticed that for me, Request.HttpContext.Connection.RemoteIpAddress gave the same result as my code above. Both return the IP address of the client, not the server where webapi resides.

I did not use this code in program.cs:

builder.Services.Configure(options => { options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; });

It works without this code

like image 122
Yogi Avatar answered Feb 04 '26 10:02

Yogi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!