纽威
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

398 lines
16 KiB

3 years ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net;
  5. using System.Text;
  6. using System.Text.RegularExpressions;
  7. using System.Web;
  8. namespace NFine.Code
  9. {
  10. public class WebHelper
  11. {
  12. #region ResolveUrl(解析相对Url)
  13. /// <summary>
  14. /// 解析相对Url
  15. /// </summary>
  16. /// <param name="relativeUrl">相对Url</param>
  17. public static string ResolveUrl(string relativeUrl)
  18. {
  19. if (string.IsNullOrWhiteSpace(relativeUrl))
  20. return string.Empty;
  21. relativeUrl = relativeUrl.Replace("\\", "/");
  22. if (relativeUrl.StartsWith("/"))
  23. return relativeUrl;
  24. if (relativeUrl.Contains("://"))
  25. return relativeUrl;
  26. return VirtualPathUtility.ToAbsolute(relativeUrl);
  27. }
  28. #endregion
  29. #region HtmlEncode(对html字符串进行编码)
  30. /// <summary>
  31. /// 对html字符串进行编码
  32. /// </summary>
  33. /// <param name="html">html字符串</param>
  34. public static string HtmlEncode(string html)
  35. {
  36. return HttpUtility.HtmlEncode(html);
  37. }
  38. /// <summary>
  39. /// 对html字符串进行解码
  40. /// </summary>
  41. /// <param name="html">html字符串</param>
  42. public static string HtmlDecode(string html)
  43. {
  44. return HttpUtility.HtmlDecode(html);
  45. }
  46. #endregion
  47. #region UrlEncode(对Url进行编码)
  48. /// <summary>
  49. /// 对Url进行编码
  50. /// </summary>
  51. /// <param name="url">url</param>
  52. /// <param name="isUpper">编码字符是否转成大写,范例,"http://"转成"http%3A%2F%2F"</param>
  53. public static string UrlEncode(string url, bool isUpper = false)
  54. {
  55. return UrlEncode(url, Encoding.UTF8, isUpper);
  56. }
  57. /// <summary>
  58. /// 对Url进行编码
  59. /// </summary>
  60. /// <param name="url">url</param>
  61. /// <param name="encoding">字符编码</param>
  62. /// <param name="isUpper">编码字符是否转成大写,范例,"http://"转成"http%3A%2F%2F"</param>
  63. public static string UrlEncode(string url, Encoding encoding, bool isUpper = false)
  64. {
  65. var result = HttpUtility.UrlEncode(url, encoding);
  66. if (!isUpper)
  67. return result;
  68. return GetUpperEncode(result);
  69. }
  70. /// <summary>
  71. /// 获取大写编码字符串
  72. /// </summary>
  73. private static string GetUpperEncode(string encode)
  74. {
  75. var result = new StringBuilder();
  76. int index = int.MinValue;
  77. for (int i = 0; i < encode.Length; i++)
  78. {
  79. string character = encode[i].ToString();
  80. if (character == "%")
  81. index = i;
  82. if (i - index == 1 || i - index == 2)
  83. character = character.ToUpper();
  84. result.Append(character);
  85. }
  86. return result.ToString();
  87. }
  88. #endregion
  89. #region UrlDecode(对Url进行解码)
  90. /// <summary>
  91. /// 对Url进行解码,对于javascript的encodeURIComponent函数编码参数,应使用utf-8字符编码来解码
  92. /// </summary>
  93. /// <param name="url">url</param>
  94. public static string UrlDecode(string url)
  95. {
  96. return HttpUtility.UrlDecode(url);
  97. }
  98. /// <summary>
  99. /// 对Url进行解码,对于javascript的encodeURIComponent函数编码参数,应使用utf-8字符编码来解码
  100. /// </summary>
  101. /// <param name="url">url</param>
  102. /// <param name="encoding">字符编码,对于javascript的encodeURIComponent函数编码参数,应使用utf-8字符编码来解码</param>
  103. public static string UrlDecode(string url, Encoding encoding)
  104. {
  105. return HttpUtility.UrlDecode(url, encoding);
  106. }
  107. #endregion
  108. #region Session操作
  109. /// <summary>
  110. /// 写Session
  111. /// </summary>
  112. /// <typeparam name="T">Session键值的类型</typeparam>
  113. /// <param name="key">Session的键名</param>
  114. /// <param name="value">Session的键值</param>
  115. public static void WriteSession<T>(string key, T value)
  116. {
  117. if (key.IsEmpty())
  118. return;
  119. HttpContext.Current.Session[key] = value;
  120. }
  121. /// <summary>
  122. /// 写Session
  123. /// </summary>
  124. /// <param name="key">Session的键名</param>
  125. /// <param name="value">Session的键值</param>
  126. public static void WriteSession(string key, string value)
  127. {
  128. WriteSession<string>(key, value);
  129. }
  130. /// <summary>
  131. /// 读取Session的值
  132. /// </summary>
  133. /// <param name="key">Session的键名</param>
  134. public static string GetSession(string key)
  135. {
  136. if (key.IsEmpty())
  137. return string.Empty;
  138. string aa = HttpContext.Current.Session[key] as string;
  139. return aa;
  140. }
  141. /// <summary>
  142. /// 删除指定Session
  143. /// </summary>
  144. /// <param name="key">Session的键名</param>
  145. public static void RemoveSession(string key)
  146. {
  147. if (key.IsEmpty())
  148. return;
  149. HttpContext.Current.Session.Contents.Remove(key);
  150. }
  151. #endregion
  152. #region Cookie操作
  153. /// <summary>
  154. /// 写cookie值
  155. /// </summary>
  156. /// <param name="strName">名称</param>
  157. /// <param name="strValue">值</param>
  158. public static void WriteCookie(string strName, string strValue)
  159. {
  160. HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
  161. if (cookie == null)
  162. {
  163. cookie = new HttpCookie(strName);
  164. }
  165. cookie.Value = strValue;
  166. HttpContext.Current.Response.AppendCookie(cookie);
  167. }
  168. /// <summary>
  169. /// 写cookie值
  170. /// </summary>
  171. /// <param name="strName">名称</param>
  172. /// <param name="strValue">值</param>
  173. /// <param name="strValue">过期时间(分钟)</param>
  174. public static void WriteCookie(string strName, string strValue, int expires)
  175. {
  176. HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
  177. if (cookie == null)
  178. {
  179. cookie = new HttpCookie(strName);
  180. }
  181. cookie.Value = strValue;
  182. cookie.Expires = DateTime.Now.AddMinutes(expires);
  183. HttpContext.Current.Response.AppendCookie(cookie);
  184. }
  185. /// <summary>
  186. /// 读cookie值
  187. /// </summary>
  188. /// <param name="strName">名称</param>
  189. /// <returns>cookie值</returns>
  190. public static string GetCookie(string strName)
  191. {
  192. if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
  193. {
  194. return HttpContext.Current.Request.Cookies[strName].Value.ToString();
  195. }
  196. return "";
  197. }
  198. /// <summary>
  199. /// 删除Cookie对象
  200. /// </summary>
  201. /// <param name="CookiesName">Cookie对象名称</param>
  202. public static void RemoveCookie(string CookiesName)
  203. {
  204. HttpCookie objCookie = new HttpCookie(CookiesName.Trim());
  205. objCookie.Expires = DateTime.Now.AddYears(-5);
  206. HttpContext.Current.Response.Cookies.Add(objCookie);
  207. }
  208. #endregion
  209. #region GetFileControls(获取客户端文件控件集合)
  210. /// <summary>
  211. /// 获取有效客户端文件控件集合,文件控件必须上传了内容,为空将被忽略,
  212. /// 注意:Form标记必须加入属性 enctype="multipart/form-data",服务器端才能获取客户端file控件.
  213. /// </summary>
  214. public static List<HttpPostedFile> GetFileControls()
  215. {
  216. var result = new List<HttpPostedFile>();
  217. var files = HttpContext.Current.Request.Files;
  218. if (files.Count == 0)
  219. return result;
  220. for (int i = 0; i < files.Count; i++)
  221. {
  222. var file = files[i];
  223. if (file.ContentLength == 0)
  224. continue;
  225. result.Add(files[i]);
  226. }
  227. return result;
  228. }
  229. #endregion
  230. #region GetFileControl(获取第一个有效客户端文件控件)
  231. /// <summary>
  232. /// 获取第一个有效客户端文件控件,文件控件必须上传了内容,为空将被忽略,
  233. /// 注意:Form标记必须加入属性 enctype="multipart/form-data",服务器端才能获取客户端file控件.
  234. /// </summary>
  235. public static HttpPostedFile GetFileControl()
  236. {
  237. var files = GetFileControls();
  238. if (files == null || files.Count == 0)
  239. return null;
  240. return files[0];
  241. }
  242. #endregion
  243. #region HttpWebRequest(请求网络资源)
  244. /// <summary>
  245. /// 请求网络资源,返回响应的文本
  246. /// </summary>
  247. /// <param name="url">网络资源地址</param>
  248. public static string HttpWebRequest(string url)
  249. {
  250. return HttpWebRequest(url, string.Empty, Encoding.GetEncoding("utf-8"));
  251. }
  252. /// <summary>
  253. /// 请求网络资源,返回响应的文本
  254. /// </summary>
  255. /// <param name="url">网络资源Url地址</param>
  256. /// <param name="parameters">提交的参数,格式:参数1=参数值1&amp;参数2=参数值2</param>
  257. public static string HttpWebRequest(string url, string parameters)
  258. {
  259. return HttpWebRequest(url, parameters, Encoding.GetEncoding("utf-8"), true);
  260. }
  261. /// <summary>
  262. /// 请求网络资源,返回响应的文本
  263. /// </summary>
  264. /// <param name="url">网络资源地址</param>
  265. /// <param name="parameters">提交的参数,格式:参数1=参数值1&amp;参数2=参数值2</param>
  266. /// <param name="encoding">字符编码</param>
  267. /// <param name="isPost">是否Post提交</param>
  268. /// <param name="contentType">内容类型</param>
  269. /// <param name="cookie">Cookie容器</param>
  270. /// <param name="timeout">超时时间</param>
  271. public static string HttpWebRequest(string url, string parameters, Encoding encoding, bool isPost = false,
  272. string contentType = "application/x-www-form-urlencoded", CookieContainer cookie = null, int timeout = 120000)
  273. {
  274. var request = (HttpWebRequest)WebRequest.Create(url);
  275. request.Timeout = timeout;
  276. request.CookieContainer = cookie;
  277. if (isPost)
  278. {
  279. byte[] postData = encoding.GetBytes(parameters);
  280. request.Method = "POST";
  281. request.ContentType = contentType;
  282. request.ContentLength = postData.Length;
  283. using (Stream stream = request.GetRequestStream())
  284. {
  285. stream.Write(postData, 0, postData.Length);
  286. }
  287. }
  288. var response = (HttpWebResponse)request.GetResponse();
  289. string result;
  290. using (Stream stream = response.GetResponseStream())
  291. {
  292. if (stream == null)
  293. return string.Empty;
  294. using (var reader = new StreamReader(stream, encoding))
  295. {
  296. result = reader.ReadToEnd();
  297. }
  298. }
  299. return result;
  300. }
  301. #endregion
  302. #region 去除HTML标记
  303. /// <summary>
  304. /// 去除HTML标记
  305. /// </summary>
  306. /// <param name="NoHTML">包括HTML的源码 </param>
  307. /// <returns>已经去除后的文字</returns>
  308. public static string NoHtml(string Htmlstring)
  309. {
  310. //删除脚本
  311. Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
  312. //删除HTML
  313. Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
  314. Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
  315. Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
  316. Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
  317. Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
  318. Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
  319. Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
  320. Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
  321. Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
  322. Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
  323. Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
  324. Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
  325. Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
  326. Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
  327. Htmlstring = Regex.Replace(Htmlstring, @"&hellip;", "", RegexOptions.IgnoreCase);
  328. Htmlstring = Regex.Replace(Htmlstring, @"&mdash;", "", RegexOptions.IgnoreCase);
  329. Htmlstring = Regex.Replace(Htmlstring, @"&ldquo;", "", RegexOptions.IgnoreCase);
  330. Htmlstring.Replace("<", "");
  331. Htmlstring = Regex.Replace(Htmlstring, @"&rdquo;", "", RegexOptions.IgnoreCase);
  332. Htmlstring.Replace(">", "");
  333. Htmlstring.Replace("\r\n", "");
  334. Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
  335. return Htmlstring;
  336. }
  337. #endregion
  338. #region 格式化文本(防止SQL注入)
  339. /// <summary>
  340. /// 格式化文本(防止SQL注入)
  341. /// </summary>
  342. /// <param name="str"></param>
  343. /// <returns></returns>
  344. public static string Formatstr(string html)
  345. {
  346. System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[\s\S]+</script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  347. System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  348. System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" on[\s\S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  349. System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[\s\S]+</iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  350. System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  351. System.Text.RegularExpressions.Regex regex10 = new System.Text.RegularExpressions.Regex(@"select", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  352. System.Text.RegularExpressions.Regex regex11 = new System.Text.RegularExpressions.Regex(@"update", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  353. System.Text.RegularExpressions.Regex regex12 = new System.Text.RegularExpressions.Regex(@"delete", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  354. html = regex1.Replace(html, ""); //过滤<script></script>标记
  355. html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性
  356. html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件
  357. html = regex4.Replace(html, ""); //过滤iframe
  358. html = regex10.Replace(html, "s_elect");
  359. html = regex11.Replace(html, "u_pudate");
  360. html = regex12.Replace(html, "d_elete");
  361. html = html.Replace("'", "’");
  362. html = html.Replace("&nbsp;", " ");
  363. return html;
  364. }
  365. #endregion
  366. }
  367. }