C# 在 ASP.NET Web API 中获取 Web Api 消费者 IP 地址和主机名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15712720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 17:41:33  来源:igfitidea点击:

Get Web Api consumer IP Address and HostName in ASP.NET Web API

c#asp.net-web-api

提问by SOF User

I have hosted Web Api developed in ASP.net. I want if someone call my API so I can log in database so later on if I want to reject request from particular id using C#.

我托管了在 ASP.net 中开发的 Web Api。我想如果有人调用我的 API 以便稍后我可以登录数据库,如果我想使用 C# 拒绝来自特定 id 的请求。

What is best practice to get consumer IP and HostName?

获取消费者 IP 和主机名的最佳实践是什么?

public static string GetIP4Address()
  {
    string IP4Address = String.Empty;

    foreach (IPAddress IPA in Dns.GetHostAddresses(Request.ServerVariables["REMOTE_ADDR"].ToString())))
    {
      if (IPA.AddressFamily.ToString() == "InterNetwork")
      {
        IP4Address = IPA.ToString();
        break;
      }
    }

    if (IP4Address != String.Empty)
    {
      return IP4Address;
    }

    foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
    {
      if (IPA.AddressFamily.ToString() == "InterNetwork")
      {
        IP4Address = IPA.ToString();
        break;
      }
    }

    return IP4Address;
  }

回答by Wiktor Zychla

Resolving names sounds like a bad idea. What if you are called from a client machine that dns doesn't resolve? I tell you, dns takes forever and then fails with an exception you have to catch and log as "unknown host name".

解析名称听起来是个坏主意。如果从 dns 无法解析的客户端机器调用您怎么办?我告诉你,dns 需要永远然后失败,你必须捕获并记录为“未知主机名”的异常。

As for request address, just get it with

至于请求地址,就用

 HttpContext.Current.Request.UserHostAddress