ASP. NET uses HttpModule to implement anti-SQL injection and loading styles and JS files

Source: Internet
Author: User
Tags dotnet httpcontext

1. Create a new class to implement the IHttpModule interface code as follows:

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, processing the data submitted by the website
(1), get mode
CodeCopy CodeThe code is as follows:
URL Submission Data Get method


(2), post mode
CodeCopy CodeThe code is as follows:
Form submission Data Post method


Full code:
CodeCopy CodeThe 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>///easy to prevent SQL injection//</summary> public class Sqlhttpmodule:ihtt pmodule {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 = (HTTPAP plication) 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 submit data Post mode 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 |c Reat |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. 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>
It is important to note that this method of preventing SQL injection is still very simple and efficient in a particular small project, but it is not common, and usually we are choosing to parameterize (using ORM or ADO-based parameterization) to prevent SQL injection.
Attached: an easy way to introduce JS script to the homepage of ASP.
ASP. NET development is supported by JavaScript. In a typical project, JS files are organized in a common directory, such as the JS folder. As the project progresses, you will find more and more JS script files, and the public Footstep library is getting bigger and larger. When actually used, we usually introduce JS files in the page through <\script src= "..." type= "Text/javascript" >, and introduce more and more. Let's briefly discuss the uniform way of introducing a common scripting library on every page, without having to be a lot of <\script src= "..." in the form of "type=" "Text/javascript" >.
As we have done before, defining a page base class called BasePage, events and methods are as follows:
Code
Copy CodeThe 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 files to the head of the webpage} #region Web header Add Universal Unified JS 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.Applicat Ionpath; url = basepath + relativeurl.substring (1); url = URL. Replace ("//", "/"); } return URL; The 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. The same principle, you can also introduce other types of files, such as CSS.

ASP. NET uses HttpModule to implement anti-SQL injection and loading styles and JS files

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.