How can I get the IP address of the current request in Blazor?
Nov 24, 2020
Blazor,
ASP .NET Core Blazor,
Blazor FAQ,
IP address current request blazor,
4605 Views
This code will help you to understand how to get the IP address of the current request in Blazor?
You can use a third-party API, such as Ipify, to get the IP address of the current request in Blazor. The script api.ipify will return the IP address in JSON format. But this is a workaround. As of now, there is no way to achieve this. In the following code snippet, the IP address will be retrieved from the Ipify API through a JS interop call to the Blazor server.
[_Host.cshtml/index.html]
<script>
function GetAddress() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://api.ipify.org?format=jsonp&callback=DisplayIP";
document.getElementsByTagName("head")[0].appendChild(script);
};
function DisplayIP(response) {
document.getElementById("text").innerHTML = "Your IP Address is " + response.ip;
}
</script>
[index.razor]
@page "/"
@inject IJSRuntime jsRuntime
<button @onclick="GetIp">Get IP!!!</button>
<textarea id="text" style="width:50%;height:40px;" />
@code{
public async Task GetIp()
{
await jsRuntime.InvokeAsync<object>("GetAddress");
}
}


