Search code examples
blazorblazor-server-side

How do I get client IP and browser info in Blazor?


How do I get client information such as IP adress and browser name/version in Blazor server-side?


Solution

  • Note that this is only referring to server-side Blazor.

    "There is no a good way to do this at the moment. We will look into how we can provide make this information available to the client."

    Source: Blazor dev at Github

    Workaround

    The client makes an ajax call to the server, which then can pick up the local ip number. Javascript:

    window.GetIP = function () {
        var token = $('input[name="__RequestVerificationToken"]').val();
        var myData = {}; //if you want to post extra data
        var dataWithAntiforgeryToken = $.extend(myData, { '__RequestVerificationToken': token });
        var ip = String('');
        $.ajax({
            async: !1, //async works as well 
            url: "/api/sampledata/getip",
            type: "POST",
            data: dataWithAntiforgeryToken,
            success: function (data) {
                ip = data;
                console.log('Got IP: ' + ip);
            },
            error: function () {
                console.log('Failed to get IP!');
            }
        });
        return ip;
    };
    

    Backend (ASP.NET Core 3.0):

        [HttpPost("[action]")]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public string GetIP()
        {
            return HttpContext.Connection.RemoteIpAddress?.ToString();
        }
    

    Note that this is not secure, the ipnumber can be spoofed so don't use for anything important.