asp.net USES HttpModule for anti sql injection

  • 2020-05-07 19:27:47
  • OfStack

1. Create a new class to implement IHttpModule interface
code
 
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 selected the AcquireRequestState event, why not the Begin_Request event? This is because we may be using session for processing, while the Begin_Request event has not yet loaded the session state (see this article for HttpModule).
2. Process the data submitted by the website
(1) GET mode
code
 
//url Submit data  get way  
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!"); 
} 
} 
} 

(2) POST mode
code
 
// Form submission data  post way  
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
 
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 to prevent sql injection  
/// </summary> 
public class SqlHttpModule : IHttpModule 
{ 
public void Dispose() 
{ 
} 
public void Init(HttpApplication context) 
{ 
context.AcquireRequestState += new EventHandler(context_AcquireRequestState); 
} 
/// <summary> 
///  To deal with 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 Submit data  get way  
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 way  
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> 
///  Filtering illegal keywords, which can be configured flexibly according to the project  
/// </summary> 
/// <param name="key"></param> 
/// <returns></returns> 
private bool FilterSql(string key) 
{ 
bool flag = true; 
try 
{ 
if (!string.IsNullOrEmpty(key)) 
{ 
//1 General configuration in the public file, such as xml File, 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; 
} 
} 
} 

3. Application in web project
Just 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 is important to note that this method of preventing sql injection is simple and efficient in certain small projects, but it is not universal. In general, we choose to parameterize orm or ado.net to prevent sql injection.
Attachment: asp.net easy way to introduce js script in the header of a web page
asp.net cannot be developed without the assistance of JavaScript. In a typical project, the js files are organized in a public directory such as the js folder. As the project progresses, you will find more and more js script files and a larger and larger public footstep library. When we actually use it, we usually pass it on the page < script src="..." type="text/javascript" > Form is introduced into js files, and more and more. Let's briefly discuss a common way to introduce a common script library per page, rather than many per page < script src="..." type="text/javascript" > In the form.
As we did before, we define a page base class called BasePage. The events and methods are as follows:
Code
 
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 to the page header js And other documents  
} 
#region  Add a general system to the header 1js file  
private void AddHeaderJs() 
{ 
string jsPath = "~/js/"; 
string filePath = Server.MapPath(jsPath); 
Literal lit = 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)); 
} 
lit.Text = sb.ToString(); 
Header.Controls.AddAt(1, lit); 
} 
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 
} 
} 

This simply solves the problem of introducing public js. By the same token, you can also introduce other types of files, such as css, etc.
demo download

Related articles: