ASP.NET 自定义URL重写

简介:
一.功能说明:
可以解决类似 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上增加通配符配置;


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


 




目录
相关文章
|
Web App开发 编解码 运维
LNMP详解(十二)——Nginx URL重写实战
LNMP详解(十二)——Nginx URL重写实战
339 2
|
开发框架 JSON .NET
ASP.NET Core 自定义配置警告信息
自定义配置警告信息需要在 startup 类中的 ConfigureService 方法中进行配置示例: // 注册 控制器服务 services.AddControllers(configure: setup => { setup.ReturnHttpNotAcceptable = true; ...
596 0
|
开发框架 中间件 .NET
asp.net core 自定义中间件【以dapper为例】
asp.net core 自定义中间件【以dapper为例】
475 88
|
开发框架 搜索推荐 中间件
中间件应用路由和URL重写
【5月更文挑战第2天】中间件应用路由和URL重写
351 3
中间件应用路由和URL重写
|
开发框架 前端开发 .NET
Asp.net Webapi 的 Post 方法不能把参数加到 URL 中?试试这样写
Asp.net Webapi 的 Post 方法不能把参数加到 URL 中?试试这样写
496 0
|
JavaScript Windows
VUE部署到IIS中报404错误解决方案-配置URL重写
VUE部署到IIS中报404错误解决方案-配置URL重写
1439 0
|
开发框架 中间件 .NET
ASP.NET CORE 自定义中间件
ASP.NET CORE 自定义中间件
333 0
|
存储 开发框架 前端开发
ASP.NET 中验证的自定义返回和统一社会信用代码的内置验证实现
本文介绍 ASP.NET 中内置的验证功能,并介绍如何自定义验证返回信息,最后以统一社会信用代码为例,实现自定义的数据验证。
644 0
ASP.NET 中验证的自定义返回和统一社会信用代码的内置验证实现
|
iOS开发
解决alert在ios版微信中显示url的问题(重写alert)
解决alert在ios版微信中显示url的问题(重写alert)
391 0