【问题标题】:How to get users IP from Azure cloud app service如何从 Azure 云应用服务获取用户 IP
【发布时间】:2020-08-04 13:18:37
【问题描述】:

我正在尝试使用以下代码获取用户 IP 以了解他们所在的国家/地区,但是当我将 MVC Core 发布到 Azure 中的应用服务时,IP 地址作为来自荷兰的 IP 返回并分配对微软公司来说,这是因为它托管在云中并且正在拉取云IP吗?如果是这样,我该如何解决?

string info = new WebClient().DownloadString("http://ipinfo.io");
            return JsonConvert.DeserializeObject<IpInfo>(info);

【问题讨论】:

  • 嗯,你是从服务器发出请求吧?那么它会是服务器的 IP 地址吗?
  • 这不是你的做法。正如@juunas 所说,这只会给你服务器的IP。如果您需要在您的网站上获取访问者的 IP,您首先需要捕获它,然后您将能够使用 ipinfo.io API 获取更多信息。你需要做更多的研究如何做到这一点,因为你今天已经解决了你的问题。

标签: c# azure model-view-controller asp.net-core-mvc ip


【解决方案1】:

试试下面的代码,它在现场可用:https://dotnetfiddle.net/4LRFYp

using System;
using System.Net;
using Newtonsoft.Json;

public class GetGeoLocation
{
    public IPData GetIPGeoLocation(string IP)
    {
        WebClient client = new WebClient();
        // Make an api call and get response.
        try
        {
            string response = client.DownloadString("http://ip-api.com/json/" + IP);
            //Deserialize response JSON
            IPData ipdata = JsonConvert.DeserializeObject<IPData>(response);
            if (ipdata.status == "fail")
            {
                throw new Exception("Invalid IP");
            }

            return ipdata;
        }
        catch (Exception)
        {
            throw;
        }
    }

    public static void Main()
    {
        IPData ipdata = new GetGeoLocation().GetIPGeoLocation("208.80.152.201");
        Console.WriteLine(ipdata.status + " - Your IP belongs to '" + ipdata.region + " - " + ipdata.country + "'");
    }
}

public class IPData
{
    public string status { get; set; }
    public string country { get; set; }
    public string countryCode { get; set; }
    public string region { get; set; }
    public string regionName { get; set; }
    public string city { get; set; }
    public string zip { get; set; }
    public string lat { get; set; }
    public string lon { get; set; }
    public string timezone { get; set; }
    public string isp { get; set; }
    public string org { get; set; }
    public string @as { get; set; }
    public string query { get; set; }
}

【讨论】:

    【解决方案2】:

    这是你可以使用的代码:

        var origin = Request.Headers.ContainsKey("CLIENT-IP") ? Request.Headers["CLIENT-IP"][0] : "";
    

    其中 Request 是 HTTP 请求对象

    【讨论】:

      猜你喜欢
      • 2017-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 2014-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多