#region 获取mvc 模型绑定的错误 /// <summary> /// 获得某个属性的错误ModelState错误信息 /// </summary> /// <param name="modelState"></param> /// <param name="attribute"></param> /// <returns></returns> public static string GetModeStateErrorByAttribute(ModelStateDictionary modelState, string attribute) { string errorMessage = string.Empty; var allError = modelState[attribute]; if (allError != null) { foreach (var item in allError.Errors) { errorMessage += item.ErrorMessage; } } return errorMessage; } /// <summary> /// 得到所有属性的错误信息 /// </summary> /// <param name="modelState"></param> /// <returns></returns> public static string GetModeStateErrorByAttribute(ModelStateDictionary modelState) { string errorMessage = string.Empty; foreach (var item in modelState.Keys) { errorMessage += GetModeStateErrorByAttribute(modelState, item); } return errorMessage; } #endregion 获取mvc 模型绑定的错误 #region GET POST 数据方法 private static string PostHttpWebRequest(string data, string url) { string result = null; try { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); byte[] requestBytes = System.Text.Encoding.UTF8.GetBytes(data); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; req.ContentLength = requestBytes.Length; Stream requestStream = req.GetRequestStream(); requestStream.Write(requestBytes, 0, requestBytes.Length); requestStream.Close(); HttpWebResponse res = (HttpWebResponse)req.GetResponse(); StreamReader sr = new StreamReader(res.GetResponseStream()); result = sr.ReadToEnd(); sr.Close(); res.Close(); } catch (Exception ex) { throw; } return result; } private static string PostWebRequestAndCookie(string postData, string url) { Encoding encoding = Encoding.GetEncoding("utf-8"); byte[] bytesToPost = encoding.GetBytes(postData); CookieContainer cookieCon = new CookieContainer(); cookieCon.Add(new Cookie { Name = "zhud", Value = "true", Domain = "tiny1.yaolan.com" }); HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url); httpRequest.CookieContainer = cookieCon; httpRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; httpRequest.ContentType = "application/x-www-form-urlencoded"; httpRequest.Method = "POST"; httpRequest.ContentLength = bytesToPost.Length; Stream requestStream = httpRequest.GetRequestStream(); requestStream.Write(bytesToPost, 0, bytesToPost.Length); requestStream.Close(); Stream responseStream = httpRequest.GetResponse().GetResponseStream(); string stringResponse = string.Empty; StreamReader responseReader = new StreamReader(responseStream, Encoding.UTF8); stringResponse = responseReader.ReadToEnd(); responseStream.Close(); return stringResponse; } public static string PostWebRequest(string data, string url) { string result = null; try { WebRequest request = WebRequest.Create(url); request.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(data); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = byteArray.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); WebResponse response = request.GetResponse(); dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); result = reader.ReadToEnd(); reader.Close(); response.Close(); } catch (Exception ex) { throw; } return result; } public static string GetWebRequest(string url) { string result = null; try { WebRequest webRequest = WebRequest.Create(url); // webRequest.Headers.Add("Cookie", Request.Headers["Cookie"]); WebResponse webResponse = webRequest.GetResponse(); Stream stream = webResponse.GetResponseStream(); StreamReader sr = new StreamReader(stream, Encoding.GetEncoding("UTF-8")); result = sr.ReadToEnd(); webResponse.Close(); stream.Close(); } catch (Exception ex) { throw; } return result; } public static string PostWebClient(NameValueCollection data, string url) { string result = null; try { System.Net.WebClient webClient = new System.Net.WebClient(); byte[] byRemoteInfo = webClient.UploadValues(url, "POST", data); result = System.Text.Encoding.UTF8.GetString(byRemoteInfo); } catch (Exception ex) { throw; } return result; } public static string GetWebClint(string url) { string result = null; try { System.Net.WebClient webClient = new System.Net.WebClient(); result = webClient.DownloadString(url); } catch (Exception ex) { throw; } return result; } #endregion GET POST 数据方法 public static string UserHostAddress { get { return HttpContext.Current.Request.UserHostAddress; } } /// <summary> /// ip是否有效 /// </summary> /// <returns></returns> public static bool IPIsValid { get { bool ipIsValid = false; foreach (var item in IPLimitList) { if (HttpContext.Current.Request.UserHostAddress.Contains(item.Replace("*", string.Empty))) { ipIsValid = true; break; } } return ipIsValid; } } public static DateTime WeekStartTime { get { DateTime dt = DateTime.Now; int dayOfWeek = -1 * (int)dt.DayOfWeek; DateTime weekStartTime = dt.AddDays(dayOfWeek + 1); if (dayOfWeek == 0) { weekStartTime = weekStartTime.AddDays(-7); } return weekStartTime.Date; } } public static DateTime WeekEndTime { get { return WeekStartTime.AddDays(7); } } /// <summary> /// xml序列化 /// </summary> /// <param name="type"></param> /// <param name="obj"></param> /// <returns></returns> public static string XmlSerializer<T>(T obj) { System.IO.StringWriter stringWriter = new System.IO.StringWriter(); try { System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T)); xmlSerializer.Serialize(stringWriter, obj); } catch (Exception ex) { throw; } return stringWriter.ToString(); } /// <summary> /// xml反序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="xml"></param> /// <returns></returns> public static T XmlDeserialize<T>(string xml) { System.IO.StringReader stringReader = new System.IO.StringReader(xml); System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T)); return (T)xmlSerializer.Deserialize(stringReader); } public static List<object> GetEnumItems(Type enumType) { var objList = new List<object>(); foreach (var item in Enum.GetValues(enumType)) { objList.Add(new { Text=item.ToString(),Value=(int)item}); } return objList; } /// <summary> /// 将对象转化为Json字符串 /// </summary> /// <typeparam name="T">源类型</typeparam> /// <param name="obj">源类型实例</param> /// <returns>Json字符串</returns> public static string ObjToJson<T>(T obj) { DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(obj.GetType()); using (MemoryStream ms = new MemoryStream()) { jsonSerializer.WriteObject(ms, obj); return Encoding.UTF8.GetString(ms.ToArray()); } } /// <summary> /// 将Json字符串转化为对象 /// </summary> /// <typeparam name="T">目标类型</typeparam> /// <param name="strJson">Json字符串</param> /// <returns>目标类型的一个实例</returns> public static T JsonToObj<T>(string strJson) { // T obj = Activator.CreateInstance<T>(); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strJson))) { DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T)); return (T)jsonSerializer.ReadObject(ms); } } public static T ChangeType<T>(object value) { return (T)Convert.ChangeType(value, typeof(T)); } /// <summary> /// 将毫秒数(从1970/1/1 到现在所经历的毫秒数)转化为本地时区的时间 /// </summary> /// <param name="ltime"></param> /// <returns></returns> public static DateTime GetTimeFromInt(long ltime) { long Eticks = (long)(ltime * 10000) + new DateTime(1970, 1, 1).Ticks; DateTime dt = new DateTime(Eticks).ToLocalTime(); return dt; } /// <summary> /// 将时间变成毫秒数(从1970/1/1 到现在所经历的毫秒数) /// </summary> /// <param name="dt"></param> /// <returns></returns> public static long GetIntFromTime(DateTime dt) { DateTime dtNew = DateTime.Now.ToUniversalTime(); long Sticks = (dtNew.Ticks - new DateTime(1970, 1, 1).Ticks) / 10000; return Sticks; } public static string GetMD5(string input) { //System.Security.Cryptography.MD5CryptoServiceProvider MD5CSP = new System.Security.Cryptography.MD5CryptoServiceProvider(); //byte[] inputByte = System.Text.Encoding.Unicode.GetBytes(input); //byte[] md5Byte = MD5CSP.ComputeHash(inputByte); //md5Result = System.Text.Encoding.Unicode.GetString(md5Byte); return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(input, "SHA1").ToLower(); }
.net 常用方法
时间: 2024-10-11 06:32:19