一.功能说明:

可以解决类似 http://****/news 情形,Url路径支持正则匹配。


二.操作步骤:
1.增加URL重写模块:
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;
/// <summary>
/// URL重写Module
/// </summary>
public class UrlRewriteModule : IHttpModule
{
    #region IHttpModule Members
    public virtual void Init(HttpApplication context)
    {
        context.BeginRequest += ApplicationBeginRequest;
    } 
    public virtual void Dispose()
    {
    }
    #endregion
    public bool IsExcludedPath(string relUrl)
    {
        string fileExt = Path.GetExtension(relUrl);
        if (!string.IsNullOrEmpty(fileExt)
            && (fileExt.ToLower() == ".axd" ||
            fileExt.ToLower() == ".jpg" ||
            fileExt.ToLower() == ".png" ||
            fileExt.ToLower() == ".gif" ||
            fileExt.ToLower() == ".swf" ||
            fileExt.ToLower() == ".bmp"
            ))
        {
            return true;
        }
        return false;
    }
    /// <summary>
    /// 
 
    /// </summary>
    /// <param name="source"></param>
    /// <param name="e"></param>
    public void ApplicationBeginRequest(object source, EventArgs e)
    {
        var application = (HttpApplication)source;
        HttpContext context = application.Context;
        try
        {
            string path = context.Request.Path;
            string file = Path.GetFileName(path);
            if (IsExcludedPath(path))
            {
                return;
            }
            if (file != null && HttpContext.Current != null)
            {
                string rewriteConfig = HttpContext.Current.Server.MapPath("~/Config/RewriterConfig.config");
                if (File.Exists(rewriteConfig))
                {
                    var xml = new XmlDocument();
                    xml.Load(rewriteConfig);
                    XmlNodeList rules = xml.SelectNodes("RewriterConfig/Rules/RewriterRule");
                    if (rules != null)
                    {
                        foreach (XmlNode rule in rules)
                        {
                            string lookFor = "";
                            string sendTo = "";
                            XmlNode lookForNode = rule.SelectSingleNode("LookFor");
                            if (lookForNode != null)
                            {
                                lookFor = lookForNode.InnerText;
                            }
                            XmlNode sendToNode = rule.SelectSingleNode("SendTo");
                            if (sendToNode != null)
                            {
                                sendTo = sendToNode.InnerText;
                            }
                            if (!string.IsNullOrEmpty(lookFor) && !string.IsNullOrEmpty(sendTo))
                            {
                                string regeRule = Regex.Escape(lookFor);
                                var regex = new Regex("^(?i)" + regeRule + "$", RegexOptions.Compiled);
                                //匹配无后缀时路径
                                if (string.IsNullOrEmpty(file))
                                {
                                    if (context.Request.ApplicationPath != null)
                                    {
                                        var subPath = path.Substring(context.Request.ApplicationPath.Length).TrimStart('/').TrimEnd('/');
                                        if (regex.Match(subPath).Success)
                                        {
                                            context.RewritePath(Path.Combine(context.Request.ApplicationPath, sendTo));
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    if (regex.Match(file).Success)
                                    {
                                        context.RewritePath(sendTo);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            context.Response.Clear();
            context.Response.Write(ex.Message);
            context.Response.End();
        }
    }
}
2.增加Url重写配置,放到网站根目录下Config文件夹下:~/Config/RewriterConfig.config
<?xml version="1.0"?>
<RewriterConfig>
    <Rules>
        <RewriterRule>
            <LookFor>floor</LookFor>
            <SendTo>index_floor.html</SendTo>
        </RewriterRule>
        <RewriterRule>
            <LookFor>door</LookFor>
            <SendTo>about/index_292.html</SendTo>
        </RewriterRule>
        <RewriterRule>
            <LookFor>kolani</LookFor>
            <SendTo>index_kolani.html</SendTo>
        </RewriterRule>
        <RewriterRule>
            <LookFor>nature</LookFor>
            <SendTo>index_nature.html</SendTo>
        </RewriterRule>
        <RewriterRule>
            <LookFor>mobile</LookFor>
            <SendTo>index_mobile.html</SendTo>
        </RewriterRule>
    </Rules>
</RewriterConfig>
3.在webconfig里注册HttpModule;注意有2个地方需要处理
集成模式下:
<system.webServer>
    <modules>
        <!--Url重写-->
         <add name="UrlRewriteModule" type="UrlRewriteModule" />
经典模式:在config/HttpModules.config里
<httpModules> 
    <!--Url重写-->
    <add name="UrlRewriteModule" type="UrlRewriteModule" />

4.如果是无后缀路径,比如/news,IIS6时需在IIS上增加通配符配置;




实际使用过程中,可能需要您的匹配规则进行相应的修改,代码仅供参考。



 





版权声明:本文为博主原创文章,未经博主允许不得转载。

ASP.NET 自定义URL重写 分类: ASP.NET 2014-10-31 16:05 174人阅读 评论(0) 收藏的更多相关文章

  1. ASP.NET 自定义URL重写 分类: ASP.NET 2014-10-31 16:05 175人阅读 评论(0) 收藏

    一.功能说明: 可以解决类似 http://****/news 情形,Url路径支持正则匹配. 二.操作步骤: 1.增加URL重写模块: using System; using System.IO; ...

  2. window.onload,<body onload="function()">, document.onreadystatechange, httpRequest.onreadystatechang 分类: C1_HTML/JS/JQUERY 2014-08-06 16:47 558人阅读 评论(0) 收藏

    部分内容参考:http://www.aspbc.com/tech/showtech.asp?id=1256 在开发的过程中,经常使用window.onload和body onload两种,很少使用do ...

  3. Mahout快速入门教程 分类: B10_计算机基础 2015-03-07 16:20 508人阅读 评论(0) 收藏

    Mahout 是一个很强大的数据挖掘工具,是一个分布式机器学习算法的集合,包括:被称为Taste的分布式协同过滤的实现.分类.聚类等.Mahout最大的优点就是基于hadoop实现,把很多以前运行于单 ...

  4. Improving the GPA 分类: 贪心 HDU 比赛 2015-08-08 16:12 11人阅读 评论(0) 收藏

    Improving the GPA Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others) ...

  5. Task schedule 分类: 比赛 HDU 查找 2015-08-08 16:00 2人阅读 评论(0) 收藏

    Task schedule Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total ...

  6. android开发之broadcast学习笔记 分类: android 学习笔记 2015-07-19 16:33 32人阅读 评论(0) 收藏

    android中的广播用的太多了,今天稍微总结一下. 按注册方式分为两种: 1.静态注册广播: 静态注册广播就是在androidManifest.xml文件中注册广播,假设我们要实现这样一个效果,在一 ...

  7. android开发之this.finish()的使用 分类: android 学习笔记 2015-07-18 19:05 30人阅读 评论(0) 收藏

    在一个Activity用完之后应该将之finish掉,但是,之前在学校里自己摸索着开发时并没有太注意这个问题,因为activity无论是否finish掉对功能的影响貌似都不是那么明显(这是读书时候的观 ...

  8. AndroidManifest.xml中的application中的name属性 分类: android 学习笔记 2015-07-17 16:51 116人阅读 评论(0) 收藏

    被这个不起眼的属性折磨了一天,终于解决了. 由于项目需要,要合并两个android应用,于是拷代码,拷布局文件,拷values,所有的都搞定之后程序还是频频崩溃,一直没有找到原因,学android时间 ...

  9. JavaScript概念之screen/client/offset/scroll/inner/avail的width/left 分类: JavaScript HTML+CSS 2015-05-27 16:42 635人阅读 评论(0) 收藏

    原文地址:http://caibaojian.com/js-name.html JS中获取各种宽度和距离,常常让我们混淆,各种浏览器的不兼容让我们很头疼,现在就在说说js中有哪些宽度和距离. 1.名词 ...

随机推荐

  1. maven简单配置

    maven-3.3.9下载 Maven是一个项目管理和综合工具.Maven提供了开发人员构建一个完整的生命周期框架.开发团队可以自动完成项目的基础工具建设,Maven使用标准的目录结构和默认构建生命周 ...

  2. python 端口扫描仪

    思路:使用socket进行连接测试,即客户端连接服务器. 核心代码如下: from socket import * def try_port(ip,port,protocol = SOCK_STREA ...

  3. A Font Lover

    Monaco / Consolas 有名的等宽字体. 效果不错. Linux Libertine 非常好的衬线字体. Liberation Serif 比较好. Gentium 非常好的衬线字体. B ...

  4. NUI四种提交数据方式c

    方式一: 1)前端页面 2)逻辑流参数设置 方式二: 1)前端页面 2)逻辑流参数设置 方式三:  1)前端页面 2)逻辑流参数设置 方式四: 1)前端页面 2)逻辑流参数设置

  5. Git索引

    原文: http://gitbook.liuhui998.com/7_4.html git中的索引(index)是一个存放了排好序的路径的二进制文件(通常是.git/index), 每一个条目都附带有 ...

  6. [20160804]synchronized

    class Timer{ private static int num; void add(String name){ //synchronized (this){ num++; try{ Threa ...

  7. 【leetcode】Edit Distance

    Edit Distance Given two words word1 and word2, find the minimum number of steps required to convert  ...

  8. poj 1847( floyd && spfa )

    http://poj.org/problem?id=1847 一个水题,用来熟悉熟悉spfa和floyd的. 题意:有m条的铁路,要从x,到y, 之后分别就是条铁路与其他铁路的交点.第一个输入的为有n ...

  9. poj 1035

    http://poj.org/problem?id=1035 poj的一道字符串的水题,不难,但就是细节问题我也wa了几次 题意就是给你一个字典,再给你一些字符,首先如果字典中有这个字符串,则直接输出 ...

  10. iOS coredata 级联删除

    应用场景如下,每个用户可以设定多个提醒,当删除一个用户时,应当把相关的提醒都删除,而删除一个提醒时,应当把提醒从用户信息中删除. 那么 Profile 应该建立一个如下图的relationship 而 ...