HttpModules帮你看守大门

           这是很久以前搞的一个东西了,今天翻东西的时候看到了,发上来和大家分享一下:
           这里就不说HttpModules是什么了,大家都知道,在网络上有很多关于用他重定向URL的功能,这里我让他成为一个门神,把守着我们的网站.
 1using System;
 2using System.Web;
 3using System.Xml;
 4
 5
 6namespace MyHttpModules
 7{
 8    /// <summary>
 9    /// CheckUrl 的摘要说明。
10    /// </summary>

11    public class CheckUrlModules : System.Web.IHttpModule
12    {
13        public CheckUrlModules()
14        {
15            
16        }

17        IHttpModule 成员
30
31        private void context_BeginRequest(object sender, EventArgs e)
32        {
33            HttpApplication application = (HttpApplication)sender;
34            HttpContext context = application.Context;
35            string xmlpath = System.Configuration.ConfigurationSettings.AppSettings["xmlpath"];
36            if( xmlpath!=null )
37            {
38                CheckUrl xmlconfig = new CheckUrl(context.Server.MapPath(xmlpath));
39                string url = context.Request.Url.ToString();
40                //context.Response.Write(url);
41                if( xmlconfig.IsFileUrl(url) )
42                {
43                    if( xmlconfig.IsParameter(url) )
44                    {
45                        if!xmlconfig.CheckParameter(url) )
46                        {
47                            context.Response.Redirect(System.Configuration.ConfigurationSettings.AppSettings["error"],true);
48                        }

49                    }

50                }

51            }

52        }

53    }

54}
上面是一个HttpModule的实现用到了CheckUrl,下面给出CheckUrl
  1using System;
  2using System.Xml;
  3using System.Text.RegularExpressions;
  4
  5namespace MyHttpModules
  6{
  7    /// <summary>
  8    /// CheckUrl 的摘要说明。
  9    /// </summary>

 10    public class CheckUrl
 11    {
 12        private System.Xml.XmlDocument doc;
 13        public CheckUrl(string xmlpath)
 14        {
 15            doc = new 
 16                XmlDocument();
 17            doc.Load(xmlpath);
 18        }

 19
 20        /// <summary>
 21        /// 检查部署文档中是否存在文件 true 存在,false 不存在
 22        /// </summary>
 23        /// <param name="url">url地址</param>
 24        /// <returns>bool</returns>

 25        public bool IsFileUrl(string url)
 26        {
 27            string filename = "";
 28            if( url.IndexOf("?")==-1 )
 29            {
 30                int starindex = url.LastIndexOf("/");
 31                int endindex = url.Length;
 32                filename = url.Substring(starindex+1,endindex-starindex-1);
 33            }

 34            else
 35            {
 36                int starindex = url.LastIndexOf("/");
 37                int endindex = url.LastIndexOf("?");
 38                filename = url.Substring(starindex+1,endindex-starindex-1);
 39            }

 40            //XmlNode node = doc.SelectSingleNode("/root/url[@file=\""+filename+"\"]");
 41            XmlNode node = doc.SelectSingleNode("/root/url[@file=\""+filename.ToLower()+"\"]");
 42
 43            if( node==null )
 44                return false;
 45            else
 46                return true;
 47        }

 48
 49        /// <summary>
 50        /// 检查地址是否存在参数 true 存在,false 不存在
 51        /// </summary>
 52        /// <param name="url">url地址</param>
 53        /// <returns>bool</returns>

 54        public bool IsParameter(string url)
 55        {
 56            if( url.LastIndexOf("?")==-1 )
 57                return false;
 58            else
 59                return true;
 60        }

 61
 62        private string[] Split(string str,char[] ch)
 63        {
 64            return str.Split(ch);
 65        }

 66
 67        /// <summary>
 68        /// 检查参数的合理 true 所有参数符合要求,false 有参数不符合要求
 69        /// </summary>
 70        /// <param name="url">url地址</param>
 71        /// <returns>bool</returns>

 72        public bool CheckParameter(string url)
 73        {
 74            //求出请求文件的名字
 75            string filename = "";
 76            int starindex = 0;
 77            int endindex = 0;
 78            bool status = true;
 79            if( url.IndexOf("?")==-1 )
 80            {
 81                starindex = url.LastIndexOf("/");
 82                endindex = url.Length;
 83                filename = url.Substring(starindex+1,endindex-starindex-1);
 84            }

 85            else
 86            {
 87                starindex = url.LastIndexOf("/");
 88                endindex = url.LastIndexOf("?");
 89                filename = url.Substring(starindex+1,endindex-starindex-1);
 90            }

 91            //end
 92            
 93            //求出单个参数行
 94            starindex = url.LastIndexOf("?");
 95            endindex = url.Length;
 96            char[] ch={'&'};
 97            string param_string = url.Substring(starindex+1,endindex-starindex-1);
 98            string[] param = param_string.Split(ch);
 99            //end
100
101            XmlNode node = doc.SelectSingleNode("/root/url[@file=\""+filename.ToLower()+"\"]");  //查找对应文件节点
102            if( node==null )
103                return true;   //当配置文件中没有找到对应节点时不作任何处理
104            //XmlNodeList nodelist = node.SelectNodes("parameter");    //找出所有参数
105            foreach(string s in param)
106            {
107                Parameter pa = new Parameter(s);   //分析字符串,得出参数名和参数值
108                string paramname = pa.ParamName;         //参数名
109                string paramvalue = pa.ParamValue;      //参数值
110                XmlNode paramnode = node.SelectSingleNode("parameter[@name=\""+paramname+"\"]");
111                //if( paramnode==null )
112                //{
113                //throw new System.ApplicationException(filename+"的"+paramvalue+"参数在配置文件中不存在");
114                //}
115                if( paramnode!=null )
116                {
117                    try
118                    {
119                        string temp = paramnode.Attributes["type"].Value;
120                    }

121                    catch(System.NullReferenceException)
122                    {
123                        throw new System.ApplicationException(filename+""+paramname+"参数type属性不存在");
124                    }

125                    switch( paramnode.Attributes["type"].Value )
126                    {
127                        case "int":  //对参数为int类型的检查处理
128                            try
129                            {
130                                int tempvalue = Convert.ToInt32(paramvalue);
131                                try
132                                {
133                                    string temp = paramnode.Attributes["max"].Value;
134                                }

135                                catch(System.ApplicationException)
136                                {
137                                    throw new System.ApplicationException(filename+""+paramname+"参数max属性不存在");
138                                }

139                                try
140                                {
141                                    string temp = paramnode.Attributes["min"].Value;
142                                }

143                                catch(System.ApplicationException)
144                                {
145                                    throw new System.ApplicationException(filename+""+paramname+"参数min属性不存在");
146                                }

147                                string maxvalue = paramnode.Attributes["max"].Value;
148                                string minvalue = paramnode.Attributes["min"].Value;
149                                if( minvalue=="*" && maxvalue!="*" )
150                                {
151                                    try
152                                    {
153                                        int max = Convert.ToInt32(maxvalue);
154                                        if( tempvalue>max )
155                                        {
156                                            status = false;
157                                            return status;
158                                        }

159
160                                    }

161                                    catch(System.FormatException)
162                                    {
163                                        throw new System.ApplicationException(filename+""+paramname+"参数属性max定义不能转换为int");
164                                    }

165                                }

166                                else if(minvalue!="*" && maxvalue=="*" )
167                                {
168                                    try
169                                    {
170                                        int min = Convert.ToInt32(minvalue);
171                                        if( tempvalue<min )
172                                        {
173                                            status = false;
174                                            return status;
175                                        }

176                                    }

177                                    catch(System.FormatException)
178                                    {
179                                        throw new System.ApplicationException(filename+""+paramname+"参数属性min定义不能转换为int");
180                                    }

181                                        
182                                }

183                                else if(minvalue!="*" && maxvalue!="*")
184                                {
185                                    try
186                                    {
187                                        int temp = Convert.ToInt32(minvalue);
188                                    }

189                                    catch(System.FormatException)
190                                    {
191                                        throw new System.ApplicationException(filename+""+paramname+"参数min属性不能转换为int");
192                                    }

193                                    try
194                                    {
195                                        int temp = Convert.ToInt32(maxvalue);
196                                    }

197                                    catch(System.FormatException)
198                                    {
199                                        throw new System.ApplicationException(filename+""+paramname+"参数max属性不能转换为int");
200                                    }

201                                    int min = Convert.ToInt32(minvalue);
202                                    int max = Convert.ToInt32(maxvalue);
203                                    if( tempvalue<min || tempvalue>max )
204                                    {
205                                        status = false;
206                                        return status;
207                                    }

208                                        
209                                }

210                            }

211                            catch(System.FormatException)
212                            {
213                                status = false;
214                                return status;
215                            }

216                            break;
217                        case "string":  //字符型参数的检查与处理
218                            string tempvalue2 = paramvalue;
219                            try  //检查iscn属性是否存在,如果不存在抛出异常
220                            {
221                                if( paramnode.Attributes["iscn"].Value=="true" )
222                                    tempvalue2 = System.Web.HttpUtility.UrlDecode(tempvalue2);
223                            }

224                            catch(System.NullReferenceException)
225                            {
226                                throw new System.ApplicationException(filename+""+paramname+"参数iscn属性不存在");
227                            }

228                            string nochs;
229                            try  //检查nostr属性是否存在,如果不存在抛出异常
230                            {
231                                nochs = paramnode.Attributes["nostr"].Value;
232                            }

233                            catch(System.NullReferenceException)
234                            {
235                                throw new System.ApplicationException(filename+""+paramname+"参数nostr属性不存在");
236                            }

237                            if( nochs!="*" )
238                            {
239                                //当能数值中存在nostr定义的值时就返回假
240                                foreachchar c in tempvalue2 )
241                                {
242                                    foreach(char c2 in nochs)
243                                    {
244                                        if( c==c2 )
245                                        {
246                                            return false;
247                                        }

248                                    }

249                                }

250                                //end
251                            }

252                            string regexvalue;
253                            try
254                            {
255                                regexvalue = paramnode.Attributes["regex"].Value;
256                            }

257                            catch(System.NullReferenceException)
258                            {
259                                throw new System.ApplicationException(filename+""+paramname+"参数regex属性不存在");
260                            }

261                            if( regexvalue!="*" )
262                            {
263                                Regex regex = new Regex(regexvalue);
264                                if!regex.IsMatch(tempvalue2) )
265                                    return false;
266                            }

267                            break;
268                    }

269                }

270            }

271            return status;
272        }

273    }

274                
275
276    /// <summary>
277    /// 获取参数名和参数值
278    /// </summary>

279    public class Parameter
280    {
281        private string _paramname;
282        private string _paramvalue;
283        private string _param;
284        public Parameter(string param)
285        {
286            _param = param;
287            if (IsParam)
288            {
289                char[] ch = {'='};
290                string[] tmpparms = param.Split(ch);
291                if( tmpparms.Length>2 || tmpparms.Length==0 || tmpparms.Length==1 )
292                    throw new System.ApplicationException("参数格式不正确");
293                if( tmpparms.Length==2 )
294                {
295                    _paramname = tmpparms[0];
296                    _paramvalue = tmpparms[1];
297                }

298            }

299            else
300            {
301                System.ApplicationException es = new ApplicationException("url参数格式不正确");
302                throw es;
303            }

304            
305        }

306
307        /// <summary>
308        /// 检查参数是否正确 true 表示参数格式正确,false 表示参数不正确
309        /// </summary>

310        private bool IsParam
311        {
312            get
313            
314                if( _param.IndexOf("=")==-1 )
315                    return false;
316                else
317                {
318                    int starindex = _param.IndexOf("=");
319                    int endindex = _param.LastIndexOf("=");
320                    if( starindex==endindex )
321                        return true;
322                    else
323                        return false;
324                }

325            }

326        }

327
328        /// <summary>
329        /// 获取参数名
330        /// </summary>

331        public string ParamName
332        {
333            get
334            return _paramname;}
335        }

336
337        /// <summary>
338        /// 获取参数值
339        /// </summary>

340        public string ParamValue
341        {
342            get
343            return _paramvalue; }
344        }

345    }

346}
大家看注释就知道没个的作用了
下面是一个配置文件的样子
<?xml version="1.0" encoding="utf-8" ?>
<root>
    
<url file="news_txt.aspx">
        
<parameter name="pn" type="int" max="*" min="1" />
        
<parameter name="next" type="int" max="*" min="1" />
        
<parameter name="newsid" type="int" max="*" min="0" />
    
</url>
</root>
上面就是全部代码,编译成DLL后放在你的BIN目录就好了,他可以帮你过滤URL的,看是否有非法信息,这里我只作到了对GET数据的检测,没有做POST数据的检测,大家也可以实现一下

posted on 2006-07-28 18:17  Work Log  阅读(713)  评论(2编辑  收藏  举报