Live Chat Icon For mobile
Live Chat Icon

How can I 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");
          } 
}

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.