How can I get the IP address of the current request in Blazor?

In Blazor, you can retrieve the IP address of the current request by utilizing the IHttpContextAccessor service. To do this, 

  1. Add builder.Services.AddHttpContextAccessor in your Program.cs file. 
  2. Then, inject IHttpContextAccessor into your component or service where you require the IP address. 
  3. Finally, obtain the client’s IP address using HttpContext.Connection.RemoteIpAddress. 
@page "/" 

@using Microsoft.AspNetCore.Http 
<h3> Here's an example of how to retrieve the IP address from HttpContext in Blazor</h3> 
<p>Localhost IP address: @ipAddress</p> 

@code { 
    private string? ipAddress; 
    [Inject] 
    private IHttpContextAccessor? httpContextAccessor { get; set; } 
    protected override void OnInitialized () 
    { 
        ipAddress = httpContextAccessor?.HttpContext?.Connection?.RemoteIpAddress?.ToString(); 
    } 
}