例如 '\,.等字符。有很多的文本框需要过滤。请问该怎么处理?
------解决方案--------------------------------------------------------
通过IHttpHandlerFactory,过滤TextBox、Input和Textarea中的特殊字符
通过IHttpHandlerFactory过滤特殊字符,可以做到和具体项目无关,部署起来也挺简单。
using System;
using System.IO;
using System.Web.UI;
using System.Web;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Web.Compilation;
using System.Reflection;
using System.Collections.Specialized;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace JianCaiWeb.Utils
{
public class FilterStrFactoryHandler : IHttpHandlerFactory
{
public virtual IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
{
//得到编译实例(通过反射)
PageHandlerFactory factory = (PageHandlerFactory)Activator.CreateInstance(typeof(PageHandlerFactory),true);
IHttpHandler handler = factory.GetHandler(context, requestType, url, pathTranslated);
//过滤字符串
if (requestType == "POST")
{
Page page = handler as Page;
if (page != null)
page.PreLoad += new EventHandler(FilterStrFactoryHandler_PreLoad);
}
//返回
return handler;
}
//过滤TextBox、Input和Textarea中的特殊字符
void FilterStrFactoryHandler_PreLoad(object sender, EventArgs e)
{
try
{
Page page = sender as Page;
NameValueCollection postData = page.Request.Form;
foreach (string postKey in postData)
{
Control ctl = page.FindControl(postKey);
if (ctl as TextBox != null)
{
((TextBox)ctl).Text = Common.InputText(((TextBox)ctl).Text);
continue;
}
if (ctl as HtmlInputControl != null)
{
((HtmlInputControl)ctl).Value = Common.InputText(((HtmlInputControl)ctl).Value);
continue;
}
if (ctl as HtmlTextArea != null)
{
((HtmlTextArea)ctl).Value = Common.InputText(((HtmlTextArea)ctl).Value);
continue;
}
}
}
catch { }
}
public virtual void ReleaseHandler(IHttpHandler handler)
{
}
}
}
Common.InputText的代码为:
//字符串过滤
public static string InputText(string text)
{
text = text.Trim();
if (string.IsNullOrEmpty(text))
return string.Empty;
text = Regex.Replace(text, "[\\s]{2,}", " "); //two or more spaces
text = Regex.Replace(text, "(<[b
------解决方案--------------------------------------------------------
B][r
------解决方案--------------------------------------------------------
R]/*>)+
------解决方案--------------------------------------------------------
(<[p
------解决方案--------------------------------------------------------
P](.
------解决方案--------------------------------------------------------
\\n)*?>)", "\n"); //<br>
text = Regex.Replace(text, "(\\s*&[n
------解决方案--------------------------------------------------------
N][b
------解决方案--------------------------------------------------------
B][s
------解决方案--------------------------------------------------------