如何检查本地主机是否可用?

41

在C#中,有没有一种方法可以检查应用程序是否正在本地主机上运行(而不是生产服务器上)?

我正在编写一个大规模邮件群发程序,如果它在本地主机上运行,则需要使用某个邮件队列。

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

15
一个 Web 应用程序始终在本地主机上运行 :) - Eric Petroelje
3
为什么不使用基于配置的值来指定正确的队列? - Chris Farmer
它将在被分配的位置运行,如果您不了解后端,则无法找到应用程序正在运行的位置。但是,任何正在运行的应用程序必须具有其自己的系统,称为本地主机。 - perilbrain
11个回答

83

由于评论中提供了正确的解决方案,所以我会将其发布为答案:

HttpContext.Current.Request.IsLocal 

36

那么可以考虑这样做:

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

1
虽然从大局来看,Oded的解决方案可能比仅检查本地主机更可取。 - ToddBFisher
35
Request.Url.Host 可能会返回其他内容,比如 127.0.0.1。只需使用 HttpContext.Current.Request.IsLocal。 - mhenry1384
2
如果您希望您的代码不依赖于IIS,最好避免使用HttpContext。 - Manoochehr Dadashi

22

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

由于您正在使用asp.net,您可以利用配置文件转换来确保每个环境下设置正确。


有趣,但我不认为我可以在web.config中存储变量,对吗?现在邮件队列的路径是邮件服务内的字符串。 - user547794
2
@user547794 - web.config 是关于可变性的。我已经链接到了配置转换文档。我建议你阅读一下,这样你就能看到你可以做多少事情了。 - Oded

21

看看这个是否有效:

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/


我们不需要为本地连接测试“客户端”吗?即当前连接的源解析为本地主机IP。 - undefined

8

很遗憾,core 中不再有 HttpContext.HttpRequest.IsLocal() 这个方法了。

但是,在检查 .Net 的 原始实现 后,通过检查 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的方法:https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-context?view=aspnetcore-2.1#use-httpcontext-from-custom-components - Tracy
它的工作很好。也许在未来版本中,.NET Core会添加扩展方法或助手来处理此验证。 - Digiman
在nginx反向代理后的Linux上,LocalIpAddress出于某种原因为空。 - norekhov

7

本地主机IP地址是恒定的,您可以使用它来判断是本地用户还是远程用户。

但是要注意,如果您已在生产服务器上登录,则也将被视为本地主机。

这适用于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();
}

2

或者,如果你只是针对开发环境(假设你的应用程序不在生产中运行调试!),你可以使用C#预处理指令

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

1

我知道这是一个非常老的帖子,但如果有人正在寻找一个直接的解决方案,那么你可以使用以下方法:

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

1
...自2012年8月以来已经作为答案存在。 - Hans Kesting
如果您愿意,我可以删除它 :) #无冒犯之意 - Mihir

1

just like this:

HttpContext.Current.Request.IsLocal


直截了当地说,这是最好的一个。 - Max Alexander Hanna

0

这是一种更为透明的替代方案:

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中,在View中,HttpContext只需使用Context即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接