如何在Blazor中获取客户端IP和浏览器信息? [英] How do I get client IP and browser info in Blazor?

查看:755
本文介绍了如何在Blazor中获取客户端IP和浏览器信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Blazor服务器端获取客户端信息,例如IP地址和浏览器名称/版本?

How do I get client information such as IP adress and browser name/version in Blazor 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."

来源: Blazor开发人员在Github上

客户端对服务器进行ajax调用,然后服务器可以获取本地ip号码. Javascript:

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;
};

后端(ASP.NET Core 3.0):

Backend (ASP.NET Core 3.0):

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

请注意,这是不安全的,可以欺骗ipnumber,因此不要将其用于任何重要的事情.

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

这篇关于如何在Blazor中获取客户端IP和浏览器信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆