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

二次信任 提交于 2019-12-10 16:28:49

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/57982444/how-do-i-get-client-ip-and-browser-info-in-blazor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!