首页 > 编程 > .NET > 正文

asp.net2.0 URL重写以及urlMappings问题(1)

2024-07-10 13:12:33
字体:
来源:转载
供稿:网友

    在asp.net2.0中的urlmappings倒是非常好用,可惜暂不支持正则表达式,不过,好在如果用ihttpmodule的话
不管什么样的请求都会先经过ihttpmodule这样就为url重写提供了一个好机会:

    下面是我写的一个ihttpmodule:

using system;
using system.web;

public class rewritemodule : ihttpmodule
{
    public rewritemodule()
    {
    }
    public override string tostring()
    {
        return this.gettype().tostring();
    }

    void ihttpmodule.dispose()
    {
    }
    private static system.xml.xmldocument ruledoc = null;
    private static system.xml.xmldocument getruleconfig(system.web.httpcontext app)
    {
        if (ruledoc == null)
        {
            ruledoc = new system.xml.xmldocument();
            ruledoc.load(app.server.mappath("~/rule.xml"));
        }
        return ruledoc;
    }
    public static string geturl(system.web.httpcontext cxt, string path)
    {
        system.xml.xmldocument doc = getruleconfig(cxt);
        system.xml.xmlnodelist lst = doc.getelementsbytagname("rewriterrule");
        string pat = "";
        foreach (system.xml.xmlnode nd in lst)
        {
            system.xml.xmlnodelist sub = nd.childnodes[0].childnodes;
            foreach (system.xml.xmlnode chk in sub)
            {
                pat = "^" + chk.innertext + "$";
                system.text.regularexpressions.regex reg = new system.text.regularexpressions.regex(pat, system.text.regularexpressions.regexoptions.compiled | system.text.regularexpressions.regexoptions.ignorecase);
                if (reg.ismatch(path))
                {
                    return reg.replace(path, nd.childnodes[1].innertext);
                }
            }
        }
        return null;
    }

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表