利用IHttpModule实现URL地址转发功能

using System;
using System.Web;
using System.Text.RegularExpressions;

namespace WebControlLibrary1
{
    
/// <summary>
    
/// BaseModuleRewriter 的摘要说明。
    
/// </summary>

    public abstract class BaseModuleRewriter:IHttpModule
    
{
        
public BaseModuleRewriter()
        
{
            
//
            
// TODO: 在此处添加构造函数逻辑
            
//
        }

        
IHttpModule 成员

        
protected virtual void app_AuthorizeRequest(object sender, EventArgs e)
        
{
            HttpApplication app 
= (HttpApplication)sender;
            
this.Rewrite(app.Request.Path,app);
        }


        
protected abstract void Rewrite(string requestedPath, HttpApplication app);

    }


    
public class ModulRewriter:BaseModuleRewriter
    
{
        
protected override void Rewrite(string requestedPath, HttpApplication app)
        
{
            
string strPath = requestedPath;
            
string strFileName = strPath.Substring(strPath.LastIndexOf("/")+1);
            
string strReg = @"^\d+";
            Regex reg 
= new Regex(strReg,RegexOptions.IgnoreCase);
            
if(reg.IsMatch(strFileName))
            
{
                
                
string strTruePath = strPath.Remove(strPath.LastIndexOf("/")+1,strFileName.Length);
                strTruePath 
= strTruePath+"go.aspx?id=" + reg.Match(strFileName).Value;
                HttpContext.Current.RewritePath(strTruePath);
                
//app.Server.Execute(strTruePath);
            }

            
else
            
{
                
//app.Server.Execute(strPath);
                HttpContext.Current.RewritePath(strPath);
            }

        }


    }

}


其实网上已经有很多人都实现了,但我现在自己实现了一下,以加深印象。在web.config中写入:
 <httpModules>
  <add type="WebControlLibrary1.ModulRewriter, WebControlLibrary1" name="ModuleRewriter" />
 </httpModules>
即可。
原文地址:https://www.cnblogs.com/sxlfybb/p/585138.html