asp.net 过滤网页特殊字符串
字符串过滤类 FilterStrFactoryHandler
1 using System;
2 using System.IO;
3 using System.Web.UI;
4 using System.Web;
5 using System.Configuration;
6 using System.Text.RegularExpressions;
7 using System.Web.Compilation;
8 using System.Reflection;
9 using System.Collections.Specialized;
10 using System.Web.UI.WebControls;
11 using System.Web.UI.HtmlControls;
12
13 namespace JY.Utils
14 {
15 /// <summary>
16 ///FilterStrFactoryHandler 的摘要说明
17 /// </summary>
18 public class FilterStrFactoryHandler : IHttpHandlerFactory
19 {
20 public virtual IHttpHandler GetHandler(HttpContext context, string requestType, string url,string pathTranslated)
21 {
22 //得到编译实例(通过反射)
23 PageHandlerFactory factory =(PageHandlerFactory)Activator.CreateInstance(typeof(PageHandlerFactory), true);
24 IHttpHandler handler =factory.GetHandler(context, requestType, url, pathTranslated);
25 //过滤字符串
26 if (requestType == "POST")
27 {
28 Page page = handler as Page;
29 if (page != null)
30 page.PreLoad += new EventHandler(FilterStrFactoryHandler_PreLoad);
31 }
32 //返回
33 return handler;
34 }
35
36 //过滤TextBox、Input和Textarea中的特殊字符
37 void FilterStrFactoryHandler_PreLoad(object sender, EventArgs e)
38 {
39 try
40 {
41 Page page = sender as Page;
42 NameValueCollection postData = page.Request.Form;
43 foreach (string postKey in postData)
44 {
45 Control ctl = page.FindControl(postKey);
46 if (ctl as TextBox != null)
47 {
48 ((TextBox)ctl).Text = InputText(((TextBox)ctl).Text);
49 continue;
50 }
51 if (ctl as HtmlInputControl != null)
52 {
53 ((HtmlInputControl)ctl).Value = InputText(((HtmlInputControl)ctl).Value);
54 continue;
55 }
56 if (ctl as HtmlTextArea != null)
57 {
58 ((HtmlTextArea)ctl).Value = InputText(((HtmlTextArea)ctl).Value);
59 continue;
60 }
61 }
62 }
63 catch { }
64 }
65
66 public virtual void ReleaseHandler(IHttpHandler handler)
67 {
68 }
69
70 //字符串过滤
71 public static string InputText(string text)
72 {
73 text = text.Trim();
74 if (string.IsNullOrEmpty(text))
75 return string.Empty;
76 text = Regex.Replace(text, "[\\s]{2,}", ""); //two or more spaces
77 text = Regex.Replace(text, "(<[b|B][r|R]/*>)+|(<[p|P](.|\\n)*?>)", "\n"); //<br>
78 text = Regex.Replace(text, "(\\s*&[n|N][b|B][s|S][p|P];\\s*)+", " "); //
79 text = Regex.Replace(text, "<(.|\\n)*?>", string.Empty); //any other tags
80 text = text.Replace("'", "");
81 text = text.Replace("%", "");
82 //text = text.Replace("_", "");
83 return text;
84 }
85 }
86 }
web.config配置
<httpHandlers>
<!--过滤提交给服务器的文本信息-->
<add verb="*" path="*.aspx" validate="false" type="JY.Utils.FilterStrFactoryHandler, JY.Utils"/>
</httpHandlers>

浙公网安备 33010602011771号