In Blazor, you can retrieve the IP address of the current request by utilizing the IHttpContextAccessor service. To do this,
- Add builder.Services.AddHttpContextAccessor in your Program.cs file.
- Then, inject IHttpContextAccessor into your component or service where you require the IP address.
- 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();
}
}


Share with