void Application_BeginRequest(object sender, EventArgs e)
{
//遍历Post参数,隐藏域除外
if (Regex.IsMatch(Request.RawUrl.ToLower(), @"/manager/") == false)
for (int i = 0; i < Request.Form.Count; i++)
{
if (Request.Form[i].ToString() == "__VIEWSTATE") continue;
if (IsDanger(Request.Form[i].ToString()))
{
Response.Write("您提交的内容中含有非法字符,已经被拒绝.");
Response.End();
}
}
//过滤所有Url中的危险字符串
if (Request.QueryString.Count > 0 && Regex.IsMatch(Request.RawUrl.ToLower(), @"\.aspx") == true && Regex.IsMatch(Request.RawUrl.ToLower(), @"fckeditor") == false)//如果防止截获fckeditor正常的Url,必须验证".aspx"
{
string Temp = "";
//string Url = Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.LastIndexOf("?"));
string Url = Request.RawUrl.Substring(0, Request.RawUrl.LastIndexOf("?"));
for (int i = 0; i < this.Request.QueryString.Count; i++)
{
try
{
Temp = HandleRequestParam(this.Request.QueryString[i].ToString());
Url += i == 0 ? "?" : "&";
Url += Request.QueryString.Keys[i].ToString() + "=" + Temp;
}
catch { }
}
//if (Url.Length < Request.Url.AbsoluteUri.Length)
// Response.Redirect(Url);
Context.RewritePath(Url);//可以用Response.Redirect和Context.RewritePath
}
//全站防止页面缓存
Response.Buffer = true;
Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);
Response.Expires = 0;
Response.CacheControl = "no-cache";
}
protected string HandleRequestParam(string str)
{
string RetStr = "";
char[] strC = str.ToLower().ToCharArray();
for (int i = 0; i < strC.Length; i++)
{
int num = Convert.ToInt32(strC[i]);
if (num >= 48 && num <= 57)
RetStr += strC[i].ToString();
else
break;
}
//string RetStr = str;
//if (IsDanger(str))
//{
// RetStr = "";
//}
return RetStr;
}
protected bool IsDanger(string InText)
{
string word = @"exec|insert|select|delete|update|master|truncate|char|declare|join|iframe|href|script|<|>|request";
if (InText == null)
return false;
if (Regex.IsMatch(InText, word))
return true;
return false;
}