asp.net using HttpModule to implement anti-SQL injection _ Practical skills

Source: Internet
Author: User
Tags dotnet httpcontext sql injection
1, a new class, implement IHttpModule interface
Code
Copy Code code 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 not the Begin_request event? This is because we may use the session in the process, and the Begin_request event does not load the session state (about HttpModule can refer to this article).
2, the data submitted to the site to deal with
(1), Get way
Code
Copy Code code as follows:

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
Copy Code code as follows:

Form Submit 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 code 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>
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>
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 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 Submit 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, 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))
{
General configuration in public files, such as XML files, txt text, and so on
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, in the Web project application
Just add the following configuration below the Web.config httpmodules node.
<add name= "Sqlhttpmodule" type= "DotNet.Common.WebForm.SqlHttpModule, DotNet.Common.WebForm" ></add>
It is important to note that this method of preventing SQL injection is still very simple and efficient in a particular small project, but not universal, and that we usually choose to use Parameterization (ORM or ado.net parameterization) to prevent SQL injection.
Attaching: asp.net The simple method of introducing JS script in the Head of Web page
asp.net development without the help of JavaScript. In the usual project, JS files are organized in a common directory such as the JS folder. As the project progresses, you'll find more and more JS script files, and public footsteps are getting bigger. In actual use, we are usually in the page through the <script src= "..." type= "text/javascript" > form to introduce JS files, and introduced more and more. Let's briefly discuss the unified approach to introducing a common script library on each page, rather than having a lot of <script src= "..." type= "Text/javascript" > in every page.
As we have done before, defining a page base class is called BasePage, and the events and methods are as follows:
Code
Copy Code code 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 to the head of the Web page
}
Add a generic Unified JS file #region Header
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 the introduction of public JS. The same principle, you can also introduce other types of files, such as CSS.
Demo download
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.