1. Create a class to implement the ihttpmodule Interface
Code
Copy code The Code is as follows: public class sqlhttpmodule: ihttpmodule
{
Public void dispose ()
{
}
Public void Init (httpapplication context)
{
Context. acquirerequeststate + = new eventhandler (context_acquirerequeststate );
}
}
when implementing the init method of the interface, we chose the acquirerequeststate event. Why is it not the begin_request event? This is because the session may be used during processing, and the session status has not been loaded when the begin_request event is executed (for details about httpmodule, refer to this Article ).
2. process the data submitted by the website
(1). Get method
Code copy Code the code is as follows: // get Method for URL-based data submission
If (context. request. querystring! = NULL)
{< br> for (INT I = 0; I {< br> key = context. request. querystring. keys [I];
value = context. server. urldecode (context. request. querystring [Key]);
If (! Filtersql (value)
{< br> throw new exception ("querystring (get) including dangerous SQL key word! ");
}< BR >}
(2) Post Method
CodeCopy codeThe Code is as follows: // 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! ");
}
}
}
Complete code:
Code Copy code The Code is as follows: 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>
/// SQL Injection prevention
/// </Summary>
Public class sqlhttpmodule: ihttpmodule
{
Public void dispose ()
{
}
Public void Init (httpapplication context)
{
Context. acquirerequeststate + = new eventhandler (context_acquirerequeststate );
}
/// <Summary>
/// Process 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;
// Get Method for URL submission
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 out invalid keywords, which 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 ))
{
// It is usually configured in public files, such as XML files and TXT files.
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;
}
}
}
3. Application in web projects
You only need to add the following configuration under the httpmodules node of Web. config.
<Httpmodules>
<Add name = "sqlhttpmodule" type = "DOTNET. Common. webform. sqlhttpmodule, DOTNET. Common. webform"> </Add>
</Httpmodules>
It should be noted that this method to prevent SQL injection is concise and efficient in a specific small project, but it is not universal. We usually choose parameterization (Using ORM or ado.net parameterization) to prevent SQL injection.
Appendix: Asp.net Simple Method for introducing JS scripts in the webpage Header
Javascript is indispensable for Asp.net development. In normal projects, JS files are organized in a public directory, such as a JS folder. As the project goes deeper, you will find that there are more and more JS script files, and the public step library is getting bigger and bigger. In actual use, we usually introduce JS files in the form of <SCRIPT src = "..." type = "text/JavaScript"> on the page, and more. Next we will briefly discuss how to introduce a Unified Public script library on each page, instead of having to use many <SCRIPT src = "... "type =" text/JavaScript "> format.
Like our previous practice, we define a page base class called basepage. The events and methods are as follows:
Code Copy code The Code is as follows: using system;
Using system. Data;
Using system. configuration;
Using system. Collections. Generic;
Using system. Web;
Using system. Web. Security;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. Web. UI. webcontrols. webparts;
Using system. Web. UI. htmlcontrols;
Using system. reflection;
Using system. text;
Using system. IO;
Namespace DOTNET. Common. webform
{
Using DOTNET. Common. model;
Using DOTNET. Common. util;
Public class basepage: system. Web. UI. Page
{
Public basepage ()
{
}
Protected override void oninit (eventargs E)
{
Base. oninit (E );
Addheaderjs (); // Add JS and other files to the webpage Header
}
# Add a common unified JS file to the region webpage Header
Private void addheaderjs ()
{
String jspath = "~ /JS /";
String filepath = server. mappath (jspath );
Literal tenant = new literal ();
Stringbuilder sb = new stringbuilder ();
If (! Directory. exists (filepath ))
Throw new exception ("path does not exist ");
List <string> listjs = new list <string> ();
Foreach (VAR item in directory. getfiles (filepath, "*. js", searchoption. topdirectoryonly ))
{
Listjs. Add (path. getfilename (item ));
}
Foreach (VAR jsname in listjs)
{
SB. append (scriptinclude (jspath + jsname ));
}
Gradient. Text = sb. tostring ();
Header. Controls. addat (1, callback );
}
Private string resolveheaderurl (string relativeurl)
{
String url = NULL;
If (string. isnullorempty (relativeurl ))
{
Url = string. empty;
}
Else if (! Relativeurl. startswith ("~ "))
{
Url = relativeurl;
}
Else
{
VaR basepath = httpcontext. Current. Request. applicationpath;
Url = basepath + relativeurl. substring (1 );
Url = URL. Replace ("//","/");
}
Return URL;
}
Private string scriptinclude (string URL)
{
If (string. isnullorempty (URL ))
Throw new exception ("path does not exist ");
String Path = resolveheaderurl (URL );
Return string. Format (@ "<SCRIPT src = '{0}' type = 'text/JavaScript '> </SCRIPT>", PATH );
}
# Endregion
}
}
In this way, the problem of introducing public JS is simply solved. Similarly, you can introduce other types of files, such as CSS.
Download demo