纽威
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.

397 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. return HttpContext.Current.Session[key] as string;
  139. }
  140. /// <summary>
  141. /// 删除指定Session
  142. /// </summary>
  143. /// <param name="key">Session的键名</param>
  144. public static void RemoveSession(string key)
  145. {
  146. if (key.IsEmpty())
  147. return;
  148. HttpContext.Current.Session.Contents.Remove(key);
  149. }
  150. #endregion
  151. #region Cookie操作
  152. /// <summary>
  153. /// 写cookie值
  154. /// </summary>
  155. /// <param name="strName">名称</param>
  156. /// <param name="strValue">值</param>
  157. public static void WriteCookie(string strName, string strValue)
  158. {
  159. HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
  160. if (cookie == null)
  161. {
  162. cookie = new HttpCookie(strName);
  163. }
  164. cookie.Value = strValue;
  165. HttpContext.Current.Response.AppendCookie(cookie);
  166. }
  167. /// <summary>
  168. /// 写cookie值
  169. /// </summary>
  170. /// <param name="strName">名称</param>
  171. /// <param name="strValue">值</param>
  172. /// <param name="strValue">过期时间(分钟)</param>
  173. public static void WriteCookie(string strName, string strValue, int expires)
  174. {
  175. HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
  176. if (cookie == null)
  177. {
  178. cookie = new HttpCookie(strName);
  179. }
  180. cookie.Value = strValue;
  181. cookie.Expires = DateTime.Now.AddMinutes(expires);
  182. HttpContext.Current.Response.AppendCookie(cookie);
  183. }
  184. /// <summary>
  185. /// 读cookie值
  186. /// </summary>
  187. /// <param name="strName">名称</param>
  188. /// <returns>cookie值</returns>
  189. public static string GetCookie(string strName)
  190. {
  191. if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
  192. {
  193. return HttpContext.Current.Request.Cookies[strName].Value.ToString();
  194. }
  195. return "";
  196. }
  197. /// <summary>
  198. /// 删除Cookie对象
  199. /// </summary>
  200. /// <param name="CookiesName">Cookie对象名称</param>
  201. public static void RemoveCookie(string CookiesName)
  202. {
  203. HttpCookie objCookie = new HttpCookie(CookiesName.Trim());
  204. objCookie.Expires = DateTime.Now.AddYears(-5);
  205. HttpContext.Current.Response.Cookies.Add(objCookie);
  206. }
  207. #endregion
  208. #region GetFileControls(获取客户端文件控件集合)
  209. /// <summary>
  210. /// 获取有效客户端文件控件集合,文件控件必须上传了内容,为空将被忽略,
  211. /// 注意:Form标记必须加入属性 enctype="multipart/form-data",服务器端才能获取客户端file控件.
  212. /// </summary>
  213. public static List<HttpPostedFile> GetFileControls()
  214. {
  215. var result = new List<HttpPostedFile>();
  216. var files = HttpContext.Current.Request.Files;
  217. if (files.Count == 0)
  218. return result;
  219. for (int i = 0; i < files.Count; i++)
  220. {
  221. var file = files[i];
  222. if (file.ContentLength == 0)
  223. continue;
  224. result.Add(files[i]);
  225. }
  226. return result;
  227. }
  228. #endregion
  229. #region GetFileControl(获取第一个有效客户端文件控件)
  230. /// <summary>
  231. /// 获取第一个有效客户端文件控件,文件控件必须上传了内容,为空将被忽略,
  232. /// 注意:Form标记必须加入属性 enctype="multipart/form-data",服务器端才能获取客户端file控件.
  233. /// </summary>
  234. public static HttpPostedFile GetFileControl()
  235. {
  236. var files = GetFileControls();
  237. if (files == null || files.Count == 0)
  238. return null;
  239. return files[0];
  240. }
  241. #endregion
  242. #region HttpWebRequest(请求网络资源)
  243. /// <summary>
  244. /// 请求网络资源,返回响应的文本
  245. /// </summary>
  246. /// <param name="url">网络资源地址</param>
  247. public static string HttpWebRequest(string url)
  248. {
  249. return HttpWebRequest(url, string.Empty, Encoding.GetEncoding("utf-8"));
  250. }
  251. /// <summary>
  252. /// 请求网络资源,返回响应的文本
  253. /// </summary>
  254. /// <param name="url">网络资源Url地址</param>
  255. /// <param name="parameters">提交的参数,格式:参数1=参数值1&amp;参数2=参数值2</param>
  256. public static string HttpWebRequest(string url, string parameters)
  257. {
  258. return HttpWebRequest(url, parameters, Encoding.GetEncoding("utf-8"), true);
  259. }
  260. /// <summary>
  261. /// 请求网络资源,返回响应的文本
  262. /// </summary>
  263. /// <param name="url">网络资源地址</param>
  264. /// <param name="parameters">提交的参数,格式:参数1=参数值1&amp;参数2=参数值2</param>
  265. /// <param name="encoding">字符编码</param>
  266. /// <param name="isPost">是否Post提交</param>
  267. /// <param name="contentType">内容类型</param>
  268. /// <param name="cookie">Cookie容器</param>
  269. /// <param name="timeout">超时时间</param>
  270. public static string HttpWebRequest(string url, string parameters, Encoding encoding, bool isPost = false,
  271. string contentType = "application/x-www-form-urlencoded", CookieContainer cookie = null, int timeout = 120000)
  272. {
  273. var request = (HttpWebRequest)WebRequest.Create(url);
  274. request.Timeout = timeout;
  275. request.CookieContainer = cookie;
  276. if (isPost)
  277. {
  278. byte[] postData = encoding.GetBytes(parameters);
  279. request.Method = "POST";
  280. request.ContentType = contentType;
  281. request.ContentLength = postData.Length;
  282. using (Stream stream = request.GetRequestStream())
  283. {
  284. stream.Write(postData, 0, postData.Length);
  285. }
  286. }
  287. var response = (HttpWebResponse)request.GetResponse();
  288. string result;
  289. using (Stream stream = response.GetResponseStream())
  290. {
  291. if (stream == null)
  292. return string.Empty;
  293. using (var reader = new StreamReader(stream, encoding))
  294. {
  295. result = reader.ReadToEnd();
  296. }
  297. }
  298. return result;
  299. }
  300. #endregion
  301. #region 去除HTML标记
  302. /// <summary>
  303. /// 去除HTML标记
  304. /// </summary>
  305. /// <param name="NoHTML">包括HTML的源码 </param>
  306. /// <returns>已经去除后的文字</returns>
  307. public static string NoHtml(string Htmlstring)
  308. {
  309. //删除脚本
  310. Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
  311. //删除HTML
  312. Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
  313. Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
  314. Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
  315. Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
  316. Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
  317. Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
  318. Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
  319. Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
  320. Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
  321. Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
  322. Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
  323. Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
  324. Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
  325. Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
  326. Htmlstring = Regex.Replace(Htmlstring, @"&hellip;", "", RegexOptions.IgnoreCase);
  327. Htmlstring = Regex.Replace(Htmlstring, @"&mdash;", "", RegexOptions.IgnoreCase);
  328. Htmlstring = Regex.Replace(Htmlstring, @"&ldquo;", "", RegexOptions.IgnoreCase);
  329. Htmlstring.Replace("<", "");
  330. Htmlstring = Regex.Replace(Htmlstring, @"&rdquo;", "", RegexOptions.IgnoreCase);
  331. Htmlstring.Replace(">", "");
  332. Htmlstring.Replace("\r\n", "");
  333. Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
  334. return Htmlstring;
  335. }
  336. #endregion
  337. #region 格式化文本(防止SQL注入)
  338. /// <summary>
  339. /// 格式化文本(防止SQL注入)
  340. /// </summary>
  341. /// <param name="str"></param>
  342. /// <returns></returns>
  343. public static string Formatstr(string html)
  344. {
  345. System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[\s\S]+</script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  346. System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  347. System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" on[\s\S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  348. System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[\s\S]+</iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  349. System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  350. System.Text.RegularExpressions.Regex regex10 = new System.Text.RegularExpressions.Regex(@"select", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  351. System.Text.RegularExpressions.Regex regex11 = new System.Text.RegularExpressions.Regex(@"update", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  352. System.Text.RegularExpressions.Regex regex12 = new System.Text.RegularExpressions.Regex(@"delete", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  353. html = regex1.Replace(html, ""); //过滤<script></script>标记
  354. html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性
  355. html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件
  356. html = regex4.Replace(html, ""); //过滤iframe
  357. html = regex10.Replace(html, "s_elect");
  358. html = regex11.Replace(html, "u_pudate");
  359. html = regex12.Replace(html, "d_elete");
  360. html = html.Replace("'", "’");
  361. html = html.Replace("&nbsp;", " ");
  362. return html;
  363. }
  364. #endregion
  365. }
  366. }