How to Properly Get Remote IP Address in a Blazor-Server Application?

272 Views Asked by At

I've looked around and a few questions exactly like this has been answered already however they all state the solution as what I'm currently trying to do which it STILL doesn't work... Currently, I am using a Blazor-Server app that has this line on the program.cs file:

builder.Services.AddHttpContextAccessor();

And on my one of my pages, I have this code to try and get the remote IP address of this connection:

@inject IHttpContextAccessor context;
context.HttpContext?.Connection.RemoteIpAddress?.ToString()

On my local machiene testing it returns 127.0.0.1, however when I actually host the website with IIS, the context.HttpContext is actually null. I'm curious what is the simplest and yet effective way to get the remote IP address of the user on the website then if this will not work?

Thanks!

2

There are 2 best solutions below

1
Suryateja KONDLA On
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
   options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});

app.UseForwardedHeaders();

Add this piece of code in your program.cs this will enable forwarded headers

or

var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
    if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
    {
       var ip = ip.ToString();
    }
}
0
bastrou On

This code worked for me when I insert it in host.cshtml file

 string? ip = HttpContext.Connection?.RemoteIpAddress.ToString();