• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

ASP.NET自定义URL重写分类:ASP.NET2014-10-3116:05175人阅读评论(0)收藏 ...

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
一.功能说明:
可以解决类似 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上增加通配符配置;


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


 




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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#使用SQLite数据库(asp.net/winform)发布时间:2022-07-10
下一篇:
ASP.NET入门教程:Button控件发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap