UrlHelper帮助类:

得到主机头

SQL注入验证方法

获取当前请求的原始URL

获得当前页面客户端的IP

判断是否来自搜索引擎链接

获取操作系统信息和浏览器具体信息

判断是否是跨站提交

判断当前访问是否来自浏览器软件 等等


UrlHelper源码下载


/// <summary>
/// 开发团队:yunjsonTeam
/// 官方主页:http://www.yunjson.com
/// </summary>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;
using Microsoft.Win32;
using System.Management;

namespace yunjsonTeamUtil.Helper
{
    public class UrlHelper
    {
        /// <summary>
        /// 获得当前页面客户端的IP
        /// 可以提取开启代理/cdn服务后的客户端真实IP
        /// </summary>
        /// <returns>当前页面客户端的真实IP</returns>
        public static string GetTrueIP()
        {
            string ip = string.Empty;
            string X_Forwarded_For = HttpContext.Current.Request.Headers["X-Forwarded-For"];
            if (!string.IsNullOrWhiteSpace(X_Forwarded_For))
            {
                ip = X_Forwarded_For;
            }
            else
            {
                string CF_Connecting_IP = HttpContext.Current.Request.Headers["CF-Connecting-IP"];
                if (!string.IsNullOrWhiteSpace(CF_Connecting_IP))
                {
                    ip = CF_Connecting_IP;
                }
                else
                {
                    //没开启代理 正常获取ip
                    ip = HttpContext.Current.Request.UserHostAddress;
                }
            }
            return ip;
        }
        /// <summary>
        /// 判断当前页面是否接收到了Post请求
        /// </summary>
        /// <returns>是否接收到了Post请求</returns>
        public static bool IsPost()
        {
            return HttpContext.Current.Request.HttpMethod.Equals("POST");
        }
        /// <summary>
        /// 判断当前页面是否接收到了Get请求
        /// </summary>
        /// <returns>是否接收到了Get请求</returns>
        public static bool IsGet()
        {
            return HttpContext.Current.Request.HttpMethod.Equals("GET");
        }
        /// <summary>
        /// 当前页面请求类型
        /// </summary>
        /// <returns></returns>
        public static string GetHttpMethod()
        {
            return HttpContext.Current.Request.HttpMethod;
        }
        /// <summary>
        /// 返回指定的服务器变量信息
        /// </summary>
        /// <param name="strName">服务器变量名</param>
        /// <returns>服务器变量信息</returns>
        public static string GetServerString(string strName)
        {
            //
            if (HttpContext.Current.Request.ServerVariables[strName] == null)
            {
                return "";
            }
            return HttpContext.Current.Request.ServerVariables[strName].ToString();
        }

        /// <summary>
        /// 返回上一个页面的地址
        /// </summary>
        /// <returns>上一个页面的地址</returns>
        public static string GetUrlReferrer()
        {
            string retVal = null;

            try
            {
                retVal = HttpContext.Current.Request.UrlReferrer.ToString();
            }
            catch { }

            if (retVal == null)
                return "";

            return retVal;

        }

        /// <summary>
        /// 得到当前完整主机头
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentFullHost()
        {
            HttpRequest request = System.Web.HttpContext.Current.Request;
            if (!request.Url.IsDefaultPort)
            {
                return string.Format("{0}:{1}", request.Url.Host, request.Url.Port.ToString());
            }
            return request.Url.Host;
        }

        /// <summary>
        /// 得到主机头
        /// </summary>
        /// <returns></returns>
        public static string GetHost()
        {
            return HttpContext.Current.Request.Url.Host;
        }


        /// <summary>
        /// 获取当前请求的原始 URL(URL 中域信息之后的部分,包括查询字符串(如果存在))
        /// </summary>
        /// <returns>原始 URL</returns>
        public static string GetRawUrl()
        {
            return HttpContext.Current.Request.RawUrl;
        }

        /// <summary>
        /// 判断当前访问是否来自浏览器软件
        /// </summary>
        /// <returns>当前访问是否来自浏览器软件</returns>
        public static bool IsBrowserGet()
        {
            string[] BrowserName = { "ie", "opera", "netscape", "mozilla", "konqueror", "firefox" };
            string curBrowser = HttpContext.Current.Request.Browser.Type.ToLower();
            for (int i = 0; i < BrowserName.Length; i++)
            {
                if (curBrowser.IndexOf(BrowserName[i]) >= 0)
                {
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 判断当前访问来自什么浏览器软件
        /// </summary>
        /// <returns>判断当前访问来自什么浏览器软件</returns>
        public static string GetBrowserStr()
        {
            string BrowserStr = string.Empty;
            HttpBrowserCapabilities hbc = HttpContext.Current.Request.Browser;
            string browserType = hbc.Browser.ToString();     //获取浏览器类型
            string browserVersion = hbc.Version.ToString();    //获取版本号
            BrowserStr = browserType + browserVersion;
            return BrowserStr;
        }
        /// <summary>
        /// 获取操作系统信息和浏览器具体信息
        /// </summary>
        /// <returns></returns>
        public static string GetAgentStr()
        {
            return HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"];
        }

        /// <summary>
        /// 返回当前页面是否是跨站提交
        /// </summary>
        /// <returns>当前页面是否是跨站提交</returns>
        public static bool IsCrossSitePost()
        {

            // 如果不是提交则为true
            if (!UrlHelper.IsPost())
            {
                return true;
            }
            return IsCrossSitePost(UrlHelper.GetUrlReferrer(), UrlHelper.GetHost());
        }

        /// <summary>
        /// 判断是否是跨站提交
        /// </summary>
        /// <param name="urlReferrer">上个页面地址</param>
        /// <param name="host">论坛url</param>
        /// <returns></returns>
        public static bool IsCrossSitePost(string urlReferrer, string host)
        {
            if (urlReferrer.Length < 7)
            {
                return true;
            }
            Uri u = new Uri(urlReferrer);
            return u.Host != host;
        }

        /// <summary>
        /// 判断是否来自搜索引擎链接
        /// </summary>
        /// <returns>是否来自搜索引擎链接</returns>
        public static bool IsSearchEnginesGet()
        {
            if (HttpContext.Current.Request.UrlReferrer == null)
            {
                return false;
            }
            string[] SearchEngine = { "google", "yahoo", "msn", "baidu", "sogou", "sohu", "sina", "163", "lycos", "tom", "yisou", "iask", "soso", "gougou", "zhongsou" };
            string tmpReferrer = HttpContext.Current.Request.UrlReferrer.ToString().ToLower();
            for (int i = 0; i < SearchEngine.Length; i++)
            {
                if (tmpReferrer.IndexOf(SearchEngine[i]) >= 0)
                {
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 判断来自什么搜索引擎链接
        /// </summary>
        /// <returns>判断来自什么搜索引擎链接</returns>
        public static string GetSearchEnginesGet()
        {
            if (HttpContext.Current.Request.UrlReferrer == null)
            {
                return "不是通过搜索引擎进入的";
            }
            string[] SearchEngine = { "google", "yahoo", "msn", "baidu", "sogou", "sohu", "sina", "163", "lycos", "tom", "yisou", "iask", "soso", "gougou", "zhongsou" };
            string tmpReferrer = HttpContext.Current.Request.UrlReferrer.ToString().ToLower();
            for (int i = 0; i < SearchEngine.Length; i++)
            {
                if (tmpReferrer.IndexOf(SearchEngine[i]) >= 0)
                {
                    return SearchEngine[i];
                }
            }
            return "不是通过搜索引擎进入的";
        }
        /// <summary>
        /// 获得当前完整Url地址
        /// </summary>
        /// <returns>当前完整Url地址</returns>
        public static string GetUrl()
        {
            return HttpContext.Current.Request.Url.ToString();
        }


        /// <summary>
        /// 获得指定Url参数的值
        /// </summary>
        /// <param name="strName">Url参数</param>
        /// <returns>Url参数的值</returns>
        public static string GetQueryString(string strName)
        {

            if (HttpContext.Current.Request.QueryString[strName] == null)
            {
                return String.Empty;
            }
            return HttpContext.Current.Request.QueryString[strName];

        }
        /// <summary>
        /// 获得当前页面的名称
        /// </summary>
        /// <returns>当前页面的名称</returns>
        public static string GetPageName()
        {
            string[] urlArr = HttpContext.Current.Request.Url.AbsolutePath.Split('/');
            return urlArr[urlArr.Length - 1].ToLower();
        }

        /// <summary>
        /// 返回表单或Url参数的总个数
        /// </summary>
        /// <returns></returns>
        public static int GetParamCount()
        {
            return HttpContext.Current.Request.Form.Count + HttpContext.Current.Request.QueryString.Count;
        }


        /// <summary>
        /// 获得指定表单参数的值
        /// </summary>
        /// <param name="strName">表单参数</param>
        /// <returns>表单参数的值</returns>
        public static string GetFormString(string strName)
        {
            if (HttpContext.Current.Request.Form[strName] == null)
            {
                return "";
            }
            return HttpContext.Current.Request.Form[strName];
        }

        /// <summary>
        /// 获得Url或表单参数的值, 先判断Url参数是否为空字符串, 如为True则返回表单参数的值
        /// </summary>
        /// <param name="strName">参数</param>
        /// <returns>Url或表单参数的值</returns>
        public static string GetString(string strName)
        {
            if ("".Equals(GetQueryString(strName)))
            {
                return GetFormString(strName);
            }
            else
            {
                return GetQueryString(strName);
            }
        }

        //QueryString 数据检测GET恶意数据

        private const string StrKeyWord = @".*(select|insert|delete|from|count(|drop table|update|truncate|asc(|mid(|char(|xp_cmdshell|exec master|netlocalgroup administrators|:|net user|""|or|and).*";
        private const string StrRegex = @"[-|;|,|/|(|)|[|]|}|{|%|@|*|!|']";

        /// <summary>
        /// 获取Post的数据
        /// </summary>
        public static string ValidUrlPostData()
        {
            bool result = false;
            string res = string.Empty;
            for (int i = 0; i < HttpContext.Current.Request.Form.Count; i++)
            {
                result = ValidData(HttpContext.Current.Request.Form[i].ToString());
                if (result)
                {
                    res = "检测出POST恶意数据: 【" + HttpContext.Current.Request.Form[i].ToString() + "】 URL: 【" + HttpContext.Current.Request.RawUrl + "】来源: 【" + HttpContext.Current.Request.UserHostAddress + "】";
                    break;
                }//如果检测存在漏洞
            }
            return res;
        }

        /// <summary>
        /// 获取QueryString中的数据
        /// </summary>
        public static string ValidUrlGetData()
        {
            bool result = false;
            string res = string.Empty;
            for (int i = 0; i < HttpContext.Current.Request.QueryString.Count; i++)
            {
                result = ValidData(HttpContext.Current.Request.QueryString[i].ToString());
                if (result)
                {
                    res = "检测出GET恶意数据: 【" + HttpContext.Current.Request.QueryString[i].ToString() + "】 URL: 【" + HttpContext.Current.Request.RawUrl + "】来源: 【" + HttpContext.Current.Request.UserHostAddress + "】";
                    break;
                }//如果检测存在漏洞
            }
            return res;
        }

        /// <summary>
        /// 验证是否存在注入代码
        /// </summary>
        /// <param name="inputData"></param>
        public static bool ValidData(string inputData)
        {
            //里面定义恶意字符集合
            //验证inputData是否包含恶意集合
            if (Regex.IsMatch(inputData.ToLower(), GetRegexString()))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 获取正则表达式
        /// </summary>
        /// <param name="queryConditions"></param>
        /// <returns></returns>
        private static string GetRegexString()
        {
            //构造SQL的注入关键字符
            string[] strBadChar =
        {
            "and"
            ,"exec"
            ,"insert"
            ,"select"
            ,"delete"
            ,"update"
            ,"count"
            ,"from"
            ,"drop"
            ,"asc"
            ,"char"
            ,"or"
            ,"%"
            ,";"
            ,":"
            ,"\'"
            ,"\""
            ,"-"
            ,"chr"
            ,"mid"
            ,"master"
            ,"truncate"
            ,"char"
            ,"declare"
            ,"SiteName"
            ,"net user"
            ,"xp_cmdshell"
            ,"/add"
            ,"exec master.dbo.xp_cmdshell"
            ,"net localgroup administrators"
        };

            //构造正则表达式
            string str_Regex = ".*(";
            for (int i = 0; i < strBadChar.Length - 1; i++)
            {
                str_Regex += strBadChar[i] + "|";
            }
            str_Regex += strBadChar[strBadChar.Length - 1] + ").*";

            return str_Regex;
        }

        #region 判断请求来源是否在允许的域名中
        /// <summary>
        /// 判断请求来源是否允许,允许则返回true
        /// </summary>
        public static bool IsAllowDomain
        {
            get
            {
                if (HttpContext.Current.Request.UrlReferrer == null) return false;
                string reqDomain = HttpContext.Current.Request.UrlReferrer.Host.ToLower();
                return isAllowUrl(reqDomain);
            }
        }
        /// <summary>
        /// 判断请求来源是否允许
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static bool isAllowUrl(string url)
        {
            string[] AllowDomains = new string[] {
                "yunjson.com"
            };
            foreach (string str in AllowDomains)
            {
                if (url.EndsWith(str)) return true;
            }
            return false;
        }
        #endregion
        /// <summary>
        /// 获取CPU的ID
        /// </summary>
        /// 需要引用dll:System.Management
        /// <returns></returns>
        public static string GetCPUId()
        {
            string strCpuID = "";
            try
            {
                ManagementClass mc = new ManagementClass("Win32_Processor");
                ManagementObjectCollection moc = mc.GetInstances();

                foreach (ManagementObject mo in moc)
                {
                    strCpuID = mo.Properties["ProcessorId"].Value.ToString();
                    break;
                }
            }
            catch
            {
                strCpuID = "网络请求出错了 ,请换一种方法吧";//默认给出一个
            }
            return strCpuID;

        }

        /// <summary>
        /// 获取CPU的名称
        /// </summary>
        /// <returns></returns>
        public static string GetCPUName()
        {
            RegistryKey rk = Registry.LocalMachine.OpenSubKey(@"HARDWARE\DESCRIPTION\System\CentralProcessor\0");

            object obj = rk.GetValue("ProcessorNameString");
            string CPUName = (string)obj;
            return CPUName.TrimStart();
        }
        /// <summary>
        /// 获取url重写后的地址
        /// </summary>
        /// <returns></returns>
        public static string GetUrlStr()
        {
            return HttpContext.Current.Request.Url.AbsoluteUri;
        }
    }
}