.net 常用方法
标签:des style class blog code http
#region 获取mvc 模型绑定的错误
///
/// 获得某个属性的错误ModelState错误信息
///
///
///
///
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;
}
///
/// 得到所有属性的错误信息
///
///
///
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;
}
}
///
/// ip是否有效
///
///
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);
}
}
///
/// xml序列化
///
///
///
///
public static string XmlSerializer(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();
}
///
/// xml反序列化
///
///
///
///
public static T XmlDeserialize(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 Listobject> GetEnumItems(Type enumType)
{
var objList = new Listobject>();
foreach (var item in Enum.GetValues(enumType))
{
objList.Add(new { Text=item.ToString(),Value=(int)item});
}
return objList;
}
///
/// 将对象转化为Json字符串
///
/// 源类型
/// 源类型实例
/// Json字符串
public static string ObjToJson(T obj)
{
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream())
{
jsonSerializer.WriteObject(ms, obj);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
///
/// 将Json字符串转化为对象
///
/// 目标类型
/// Json字符串
/// 目标类型的一个实例
public static T JsonToObj(string strJson)
{
// T obj = Activator.CreateInstance();
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strJson)))
{
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T));
return (T)jsonSerializer.ReadObject(ms);
}
}
public static T ChangeType(object value)
{
return (T)Convert.ChangeType(value, typeof(T));
}
///
/// 将毫秒数(从1970/1/1 到现在所经历的毫秒数)转化为本地时区的时间
///
///
///
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;
}
///
/// 将时间变成毫秒数(从1970/1/1 到现在所经历的毫秒数)
///
///
///
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 常用方法,搜素材,soscw.com
.net 常用方法
标签:des style class blog code http
原文地址:http://www.cnblogs.com/zhudongchang/p/3795112.html
评论