1 Create a new class to implement the IHttpModule interface
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Text;
Namespace DotNet.Common.WebForm
{
<summary>
Simple prevention of SQL injection
</summary>
public class Sqlhttpmodule:ihttpmodule
{
public void Dispose ()
{
}
public void Init (HttpApplication context)
{
Context. AcquireRequestState + = new EventHandler (context_acquirerequeststate);
}
<summary>
Handling SQL Injection
</summary>
<param name= "Sender" ></param>
<param name= "E" ></param>
private void Context_acquirerequeststate (object sender, EventArgs e)
{
HttpContext context = ((HttpApplication) sender). Context;
Try
{
String key = String. Empty;
String value = String. Empty;
URL Submission Data Get method
if (context. Request.QueryString = null)
{
for (int i = 0; I < context. Request.QueryString.Count; i++)
{
Key = Context. Request.querystring.keys[i];
Value = Context. Server.urldecode (context. Request.querystring[key]);
if (! Filtersql (value))
{
throw new Exception ("QueryString (GET) including dangerous SQL Key word!");
}
}
}
Form submission Data Post method
if (context. Request.Form = null)
{
for (int i = 0; I < context. Request.Form.Count; i++)
{
Key = Context. Request.form.keys[i];
if (key = = "__viewstate") continue;
Value = Context. Server.htmldecode (context. Request.form[i]);
if (! Filtersql (value))
{
throw new Exception ("Request.Form (POST) including dangerous SQL Key word!");
}
}
}
}
catch (Exception ex)
{
Throw ex;
}
}
<summary>
Filter illegal keywords, this can be flexibly configured according to the project
</summary>
<param name= "Key" ></param>
<returns></returns>
private bool Filtersql (string key)
{
BOOL flag = TRUE;
Try
{
if (!string. IsNullOrEmpty (Key))
{
General configuration in common files, such as XML files, txt text, etc.
string sqlStr = "insert |delete |select |update |exec |varchar |drop |creat |declare |truncate |cursor |begin |open|<-- |--> ";
string[] Sqlstrarr = sqlstr.split (' | ');
foreach (String strchild in Sqlstrarr)
{
if (key. ToUpper (). IndexOf (Strchild.toupper ())! =-1)
{
Flag = false;
Break
}
}
}
}
Catch
{
Flag = false;
}
return flag;
}
}
}
2 Applying in Web projects
Just add the following configuration below the httpmodules node of the Web. config.
<add name= "Sqlhttpmodule" type= "DotNet.Common.WebForm.SqlHttpModule, DotNet.Common.WebForm" ></add>
Or is:
<add name= "Sqlhttpmodule" type= "DotNet.Common.WebForm.SqlHttpModule" ></add>
The value of type is the namespace of the public class + class name
Reprinted from http://blog.csdn.net/loveheye/article/details/5948610
. NET SQL anti-injection HttpModule