首先在后台创建一个类 CommonMethods

 public class CommonMethods
  {


 }

View Code

1.常用验证方法

        #region 验证帐号
        /// <summary>
        /// 验证帐号
        /// </summary>
        /// <param name="source">字母开头,允许5-16字节,允许字母数字下划线</param>
        /// <returns></returns>
        public static bool IsAccount(string source)
        {
            return Regex.IsMatch(source, @"^[a-zA-Z][a-zA-Z0-9_]{4,15}$", RegexOptions.IgnoreCase);
        }
        #endregion

        #region 验证密码
        /// <summary>
        /// 验证密码
        /// </summary>
        /// <param name="source">以字母开头,长度在6~18之间,只能包含字母、数字和下划线</param>
        /// <returns></returns>
        public static bool IsPassword(string source)
        {
            return Regex.IsMatch(source, @"^[a-zA-Z]\w{5,17}$", RegexOptions.IgnoreCase);
        }
        #endregion

        #region 验证邮箱
        /// <summary>
        /// 验证邮箱
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static bool IsEmail(string source)
        {
            return Regex.IsMatch(source, @"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$", RegexOptions.IgnoreCase);
        }
        #endregion

        #region 验证手机
        /// <summary>
        /// 验证手机
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static bool IsPhone(string source)
        {
            return Regex.IsMatch(source, @"^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$", RegexOptions.IgnoreCase);
        }
        #endregion

        #region 身份证验证
        /// <summary>
        /// 身份证验证
        /// </summary>
        /// <param name="cardId">身份证号</param>
        /// <returns></returns>
        public bool CheckIdCard(string cardId)
        {
            if (cardId.Length == 18)
            {
                bool check = CheckIdCard18(cardId);
                return check;
            }
            else if (cardId.Length == 15)
            {
                bool check = CheckIdCard15(cardId);
                return check;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 18位身份证验证
        /// </summary>
        /// <param name="cardId">身份证号</param>
        /// <returns></returns>
        private bool CheckIdCard18(string cardId)
        {
            long n = 0;
            if (long.TryParse(cardId.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(cardId.Replace('x', '0').Replace('X', '0'), out n) == false)
            {
                return false;//数字验证
            }
            const string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(cardId.Remove(2), System.StringComparison.Ordinal) == -1)
            {
                return false;//省份验证
            }
            string birth = cardId.Substring(6, 8).Insert(6, "-").Insert(4, "-");
            DateTime time;
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证
            }
            string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
            string[] wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
            char[] ai = cardId.Remove(17).ToCharArray();
            int sum = 0;
            for (int i = 0; i < 17; i++)
            {
                sum += int.Parse(wi[i]) * int.Parse(ai[i].ToString());
            }
            int y = -1;
            Math.DivRem(sum, 11, out y);
            if (arrVarifyCode[y] != cardId.Substring(17, 1).ToLower())
            {
                return false;//校验码验证
            }
            return true;//符合GB11643-1999标准
        }
        /// <summary>
        /// 15位身份证验证
        /// </summary>
        /// <param name="cardId">身份证号</param>
        /// <returns></returns>
        private bool CheckIdCard15(string cardId)
        {
            long n = 0;
            if (long.TryParse(cardId, out n) == false || n < Math.Pow(10, 14))
            {
                return false;//数字验证
            }
            const string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(cardId.Remove(2), System.StringComparison.Ordinal) == -1)
            {
                return false;//省份验证
            }
            string birth = cardId.Substring(6, 6).Insert(4, "-").Insert(2, "-");
            DateTime time;
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证
            }
            return true;//符合15位身份证标准
        }
        #endregion

View Code

2.生成时间戳

        #region 生成时间戳
        /// <summary>
        /// 生成时间戳,标准北京时间,时区为东八区,自1970年1月1日 0点0分0秒以来的秒数 
        /// </summary>
        /// <returns></returns>
        public static string GenerateTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString(CultureInfo.InvariantCulture);
        }
        #endregion

View Code

3.生成随机数

 #region 生成随机数
        /// <summary>  
        /// 生成随机数  
        /// </summary>  
        /// <param name="length">生成字符串长度</param>  
        /// <param name="type">1.数字+字母 2.整形 3.字符 </param>  
        /// <returns></returns>  
        public static string GenerateCode(int length, int type)
        {
            int number;
            char code;
            string checkCode = String.Empty;
            var random = new Random();
            if (type == 1)
            {
                for (int i = 0; i < length; i++)
                {
                    number = random.Next();

                    if (number % 2 == 0)
                        code = (char)('0' + (char)(number % 10));
                    else
                        code = (char)('A' + (char)(number % 26));

                    checkCode += code.ToString(CultureInfo.InvariantCulture);
                }
            }
            else if (type == 2)
            {
                for (int i = 0; i < length; i++)
                {
                    number = random.Next();
                    code = (char)('0' + (char)(number % 10));
                    checkCode += code.ToString(CultureInfo.InvariantCulture);
                }
            }
            else if (type == 3)
            {
                for (int i = 0; i < length; i++)
                {
                    number = random.Next();
                    code = (char)('A' + (char)(number % 26));
                    checkCode += code.ToString(CultureInfo.InvariantCulture);
                }
            }
            return checkCode;
        }
        #endregion

View Code

4.带有“,”的字符串转成int[]

 #region 带有“,”的字符串转成int[]
        /// <summary>  
        /// 带有“,”的字符串转成int[]  
        /// </summary>  
        /// <param name="str">1,2,3,4,5,6,8,9,10,</param>  
        /// <returns></returns>  
        public static int[] StringToIntArray(string str)
        {
            int[] intArray = null;
            if (!string.IsNullOrEmpty(str))
            {
                string newStr = str.TrimEnd(',');
                intArray = newStr.Split(',').Select(v => Convert.ToInt32(v)).ToArray();
            }
            return intArray;
        }
        #endregion

View Code

5.带有“,”的字符串转成string[]

 #region 带有“,”的字符串转成string[]
        /// <summary>  
        /// 带有“,”的字符串转成string[]  
        /// </summary>  
        /// <param name="str">A,B,C,D,E,F,G,H,I,</param>  
        /// <returns></returns>  
        public static string[] StringToStrArray(string str)
        {
            string[] strArray = null;
            if (!string.IsNullOrEmpty(str))
            {
                string newStr = str.TrimEnd(',');
                strArray = newStr.Split(',');
            }
            return strArray;
        }
        #endregion

View Code

6.MD5加密

        #region 16位MD5加密
        /// <summary>
        /// 16位MD5加密
        /// </summary>
        /// <param name="encryptString">待加密的字符串</param>
        /// <returns></returns>
        public static string Md5Encrypt16(string encryptString)
        {
            var md5 = new MD5CryptoServiceProvider();
            string t2 = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(encryptString)), 4, 8);
            t2 = t2.Replace("-", "");
            return t2;
        }
        #endregion

        #region 32位MD5加密
        /// <summary>
        /// 32位MD5加密
        /// </summary>
        /// <param name="encryptString">待加密的字符串</param>
        /// <returns></returns>
        public static string Md5Encrypt32(string encryptString)
        {
            string cl = encryptString;
            MD5 md5 = MD5.Create(); //实例化一个md5对像
            // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择 
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
            // 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
            string pwd = s.Aggregate("", (current, t) => current + t.ToString("X"));
            return pwd.ToLower();
        }
        #endregion

View Code

7.Session操作方法

        #region 添加Session
        /// <summary>
        /// 添加Session
        /// </summary>
        /// <param name="strSessionName">Session对象名称</param>
        /// <param name="objValue">Session值</param>
        /// <param name="iExpires">有效期(分钟)</param>
        public static void AddSession(string strSessionName, string objValue, int iExpires)
        {
            HttpContext.Current.Session[strSessionName] = objValue;
            HttpContext.Current.Session.Timeout = iExpires;
        }
        #endregion

        #region 读取某个Session对象
        /// <summary>
        /// 读取某个Session对象值
        /// </summary>
        /// <param name="strSessionName">Session对象名称</param>
        /// <returns>Session对象值</returns>
        public static object GetSession(string strSessionName)
        {
            return HttpContext.Current.Session[strSessionName];
        }
        #endregion

        #region 删除某个Session对象
        /// <summary>
        /// 删除某个Session对象
        /// </summary>
        /// <param name="strSessionName">Session对象名称</param>
        public static void RemoveSession(string strSessionName)
        {
            HttpContext.Current.Session.Remove(strSessionName);
        }
        #endregion

View Code

Session操作方法使用方式:

            CommonMethods.AddSession("www", "123456", 10);
            var j = CommonMethods.GetSession("www");
            CommonMethods.RemoveSession("www");

8.日志文件

        #region 日志文件记录
        /// <summary>
        /// 日志文件记录
        /// </summary>
        /// <param name="ex">异常信息</param>
        public static void WriteErorrLog(Exception ex)
        {
            if (ex == null) return; //ex = null 返回  
            DateTime dt = DateTime.Now; // 设置日志时间  
            string time = dt.ToString("yyyy-MM-dd HH:mm:ss"); //年-月-日 时:分:秒  
            string logName = dt.ToString("yyyy-MM-dd"); //日志名称  
            string logPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, Path.Combine("log", logName)); //日志存放路径  
            string log = Path.Combine(logPath, string.Format("{0}.log", logName)); //路径 + 名称
            try
            {
                var info = new FileInfo(log);
                if (info.Directory != null && !info.Directory.Exists)
                {
                    info.Directory.Create();
                }
                using (var write = new StreamWriter(log, true, Encoding.GetEncoding("utf-8")))
                {
                    write.WriteLine(time);
                    write.WriteLine(ex.Message);
                    write.WriteLine("异常信息:" + ex);
                    write.WriteLine("异常堆栈:" + ex.StackTrace);
                    write.WriteLine("异常简述:" + ex.Message);
                    write.WriteLine("\r\n----------------------------------\r\n");
                    write.Flush();
                    write.Close();
                    write.Dispose();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        #endregion

View Code

 

日志文件使用方式:

try
{

}
catch (Exception ex)
{
    CommonMethods.WriteErorrLog(ex);
}

9.获取客户端的IP地址

  #region 获取客户端的IP地址
        /// <summary>
        /// 获取客户端的IP地址
        /// </summary>
        /// <returns>客户端IP地址</returns>
        public static string Get_ClientIP()
        {
            string result = HttpContext.Current.Request.Headers["X-Real-IP"];
            if (result != null)
            {
                return result;
            }
            if (HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] != null)//发出请求的远程主机的IP地址
            {
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString(CultureInfo.InvariantCulture);
            }
            else if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)//判断是否设置代理,若使用了代理
            {
                if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)//获取代理服务器的IP
                {
                    result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString(CultureInfo.InvariantCulture);
                }
                else
                {
                    result = HttpContext.Current.Request.UserHostAddress;
                }
            }
            else
            {
                result = HttpContext.Current.Request.UserHostAddress;
            }
            if (result == "::1")
                result = string.Empty;
            return result;
        }
        #endregion

View Code

 

版权声明:本文为zj19940610原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/zj19940610/p/9442563.html