0

I need to get the IP address of the client, so I did the following:

  1. Created a controller and added this action:

     [HttpGet("[action]")]
     public ActionResult IpAddress()
     {
         var remoteIpAddress = HttpContext.Connection.RemoteIpAddress;
         if (remoteIpAddress != null)
             return Ok(remoteIpAddress.ToString());
    
         return new EmptyResult();
     }
    
  2. Added the following script to my site.js:

     window.getIpAddress = () => {
         return fetch('/api/utils/ipaddress')
             .then((response) => response.text())
             .then((data) => {
                 return data
             })
     }
    
  3. Set up Startup.cs to user controllers too, also adding the following:

         app.UseForwardedHeaders(new ForwardedHeadersOptions
         {
             ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
         });
    
  4. And finally, added the following to my razor component:

     var ipAddress = await jsRuntime.InvokeAsync<string>("getIpAddress").ConfigureAwait(true);
    

I then publish to IIS and access the app.

However, the IP address is not the client's IP address (actually the value of standard gateway) but that of the machine where IIS is running!

What am I doing wrong?

Ivan-Mark Debono
  • 15,500
  • 29
  • 132
  • 263
  • See [this](https://stackoverflow.com/questions/28664686/how-do-i-get-client-ip-address-in-asp-net-core) and [this](https://stackoverflow.com/questions/35441521/remoteipaddress-is-always-null) (particularly the answer to the second one). – sellotape Apr 15 '21 at 10:05
  • @sellotape Nope doesn't work – Ivan-Mark Debono Apr 15 '21 at 11:02
  • @Ivan-Mark Debono, here's your answer https://stackoverflow.com/a/59538319/6152891 . It is also relevant to this question of yours(https://stackoverflow.com/q/66553818/6152891) . Please, let me know if you did not succeed to solve your issues – enet Apr 16 '21 at 08:50
  • @enet I was actually already using that same procedure to get the `ITrackingConsentFeature`, so I just added the IPAddress. However, it's still the server machine's gateway and not the client IP address :( – Ivan-Mark Debono Apr 16 '21 at 13:31
  • @Ivan-Mark Debono, I'll inspect things, and let you know when I get a proper solution – enet Apr 16 '21 at 14:17
  • See my answer... – enet Apr 17 '21 at 09:31
  • @Ivan-Mark Debono, please go to github and respond to the comment by BrennanConroy. He's not of the Blazor team, but he's the one who can help. , – enet Apr 19 '21 at 21:19

0 Answers0