【问题标题】:How to check if localhost如何检查本地主机
【发布时间】:2012-08-06 18:50:52
【问题描述】:

在 C# 中有没有办法检查应用程序是否在 localhost(而不是生产服务器)上运行?

我正在编写一个需要使用特定邮件队列的群发邮件程序,它是在本地主机上运行的。

if (Localhost)
{
Queue = QueueLocal;
}
else
{
Queue = QueueProduction;
}

【问题讨论】:

  • 一个网络应用程序总是在本地主机上运行:)
  • 为什么不使用某种基于配置的值来指定正确的队列?
  • 它将在分配给它的位置运行,如果您对后端一无所知,那么您将无法找到应用程序正在运行的位置。但是,任何正在运行的应用程序都必须拥有自己的系统,称为本地主机。

标签: c# asp.net .net


【解决方案1】:

作为comment 有正确的解决方案,我将其作为答案发布:

HttpContext.Current.Request.IsLocal 

【讨论】:

    【解决方案2】:

    类似的东西呢:

    public static bool OnTestingServer()
        {
            string host = HttpContext.Current.Request.Url.Host.ToLower();
            return (host == "localhost");
        }
    

    【讨论】:

    • 虽然从大局来看,Oded 的解决方案可能比简单地检查本地主机更倾向于我。
    • Request.Url.Host 可以返回其他内容,例如 127.0.0.1。只需做 HttpContext.Current.Request.IsLocal
    • 如果您希望代码独立于 IIS,最好避免依赖 HttpContext...
    【解决方案3】:

    在应用程序配置文件中使用一个值,该值将告诉您您所处的环境。

    由于您使用的是 asp.net,因此您可以使用 config file transforms 来确保您的每个环境的设置都是正确的。

    【讨论】:

    • 很有趣,但我认为我不能将变量存储在 web.config 中,可以吗?现在邮件队列的路径是邮件服务中的一个字符串。
    • @user547794 - web.config 是关于可变性的。我链接到配置转换文档。我建议你阅读一下,这样你就可以知道你能做多少。
    【解决方案4】:

    看看这是否有效:

    public static bool IsLocalIpAddress(string host)
    {
      try
      { // get host IP addresses
        IPAddress[] hostIPs = Dns.GetHostAddresses(host);
        // get local IP addresses
        IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
    
        // test if any host IP equals to any local IP or to localhost
        foreach (IPAddress hostIP in hostIPs)
        {
          // is localhost
          if (IPAddress.IsLoopback(hostIP)) return true;
          // is local address
          foreach (IPAddress localIP in localIPs)
          {
            if (hostIP.Equals(localIP)) return true;
          }
        }
      }
      catch { }
      return false;
    }
    

    参考:http://www.csharp-examples.net/local-ip/

    【讨论】:

      【解决方案5】:

      Localhost ip地址是不变的,你可以用它来判断它是本地主机还是远程用户。

      但请注意,如果您登录生产服务器,它也将被视为 localhost。

      这包括 IP v.4 和 v.6:

      public static bool isLocalhost( )
      {
          string ip = System.Web.HttpContext.Current.Request.UserHostAddress;
          return (ip == "127.0.0.1" || ip == "::1");
      }
      

      要完全确定代码在哪个服务器上运行,您可以使用 MAC 地址:

      public string GetMACAddress()
      {
          NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
          String sMacAddress = string.Empty;
          foreach (NetworkInterface adapter in nics)
          {
              if (sMacAddress == String.Empty)// only return MAC Address from first card  
              {
                  IPInterfaceProperties properties = adapter.GetIPProperties();
                  sMacAddress = adapter.GetPhysicalAddress().ToString();
              }
          } return sMacAddress;
      }
      

      来自:http://www.c-sharpcorner.com/uploadfile/ahsanm.m/how-to-get-the-mac-address-of-system-using-Asp-NetC-Sharp/

      例如与 web.config 中的 MAC 地址进行比较。

      public static bool isLocalhost( )
      {
          return GetMACAddress() == System.Configuration.ConfigurationManager.AppSettings["LocalhostMAC"].ToString();
      }
      

      【讨论】:

        【解决方案6】:

        不幸的是,核心中不再有HttpContext.HttpRequest.IsLocal()

        但是在.Net 中检查original implementation 之后,通过检查HttpContext.Connection 来重新实现相同的行为是很容易的:

        private bool IsLocal(ConnectionInfo connection)
        {
            var remoteAddress = connection.RemoteIpAddress.ToString();
        
            // if unknown, assume not local
            if (String.IsNullOrEmpty(remoteAddress))
                return false;
        
            // check if localhost
            if (remoteAddress == "127.0.0.1" || remoteAddress == "::1")
                return true;
        
            // compare with local address
            if (remoteAddress == connection.LocalIpAddress.ToString())
                return true;
        
            return false;
        }
        

        【讨论】:

        • 下面是从 asp.net CORE 2 应用程序访问 HTTPContext 的方法:docs.microsoft.com/en-us/aspnet/core/fundamentals/…
        • 效果很好。也许在功能版本中,扩展方法或帮助程序将被添加到 .NET Core 以从框中处理此验证。
        • LocalIpAddress 出于某种原因在 nginx 反向代理后面的 Linux 上为空。
        【解决方案7】:

        或者,如果您只是针对开发环境,您可以使用C# Preprocessor Directive(这是假设您的应用没有在生产环境中调试运行!):

        #if debug
        Queue = QueueLocal;
        #else
        Queue = QueueProduction;
        

        【讨论】:

          【解决方案8】:

          就像这样:

          HttpContext.Current.Request.IsLocal

          【讨论】:

          • 直截了当
          【解决方案9】:

          字符串主机名 = Request.Url.Host.ToString();

          【讨论】:

            【解决方案10】:

            我知道这是真正的旧线程,但仍然有人在寻找直接的解决方案,那么您可以使用它:

            if (HttpContext.Current.Request.Url.Host == "localhost")
            {
              //your action when app is running on localhost
            }
            

            【讨论】:

            • ... 自 2012 年 8 月以来已作为答案存在
            • 如果你想我可以删除它:) #nooffence
            【解决方案11】:

            这是另一种更透明的选择:

            public static bool IsLocal
            {
                // MVC < 6
                get 
                {
                    var authority = HttpContext.Request.Url.Authority.ToLower();
            
                    return authority == "localhost" ||
                           authority.StartsWith("localhost:");
                }
                // MVC 6+
                get 
                { 
                    return String.Compare(HttpContext.Request.Url.Host, "localhost", 
                                          StringComparison.OrdinalIgnoreCase);
                }
            }
            

            如果您Controller 中执行此操作,请在HttpContext 之后添加Current,如HttpContext.Current.Request... 中所示

            另外,在MVC 6,在ViewHttpContext 只是Context

            【讨论】:

              猜你喜欢
              • 2011-03-17
              • 2017-02-03
              • 1970-01-01
              • 2011-03-10
              • 2012-09-09
              • 1970-01-01
              • 2011-11-26
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多