Can I fool HttpRequest.Current.Request.IsLocal?

前端 未结 4 1774
-上瘾入骨i
-上瘾入骨i 2021-02-08 07:44

I\'m running a web application that displays some debugging behavior if it\'s being run locally - quotes around resource strings, etc - and I\'d like to demo the application on

4条回答
  •  花落未央
    2021-02-08 08:41

    If your server has multiple ip addresses, you'll need some extra code. The following handles multiple ip addresses, and handles CDN like cloudflare which will have the wrong ip address in the Request.UserHostAddress property.

    Code:

    private bool IsLocal()
    {
        if (Request.IsLocal)
        {
            return true;
        }
        string forwardIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        foreach (NetworkInterface netInterface in NetworkInterface.GetAllNetworkInterfaces())
        {
            IPInterfaceProperties ipProps = netInterface.GetIPProperties();
            foreach (UnicastIPAddressInformation addr in ipProps.UnicastAddresses)
            {
                string ipString = addr.Address.ToString();
                if (Request.UserHostAddress == ipString || forwardIP == ipString)
                {
                    return true;
                }
            }
        }
        return false;
    }
    

提交回复
热议问题