UrlRewriter && IIS7

为了在动态网站获得更好的url体验,往往采用url重写技术。

比如:http://blog.xujif.com/?p=268 可以重写为 http://blog.xujif.com/archives/wordpress-rss-feed-error/

更多介绍:传送门:http://msdn.microsoft.com/zh-cn/library/ms972974.aspx

IIS级别可以实现url重写。这里说的是asp.net级别的

在asp.net级别的url重写中,用到一个HttpModule模块

举个例子:新建类库

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
namespace UrlRewrite
{
    public class UrlRewrite : IHttpModule
    {
        public void Dispose()
        {
            // throw new NotImplementedException();
        }
        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(BeginRequest);
        }
        public void BeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = sender as HttpApplication;
            HttpUrlRewrite(app.Context);
        }
        public void HttpUrlRewrite(HttpContext context)
        {
            string url = context.Request.Url.ToString();
            context.RewritePath("~/Default.aspx", null, "url=" + url);
        }
    }
}

这个例子是把对网站的所有请求都转发给~/Default.aspx,然后把请求的url作为参数传递它。

如果在Default.aspx.cs里

1
2
3
4
5
6
7
protected void Page_Load(object sender, EventArgs e)
 
{
 
Response.Write(Request["url"]);
 
}

然后在web.config里注册一下啊   (确保UrlRewrite.dll已经编译到bin目录了)

1
2
3
4
5
6
7
<system.web>
    <httpModules>
        <add name="UrlRewrite" type="UrlRewrite.UrlRewrite,UrlRewrite"/>
    </httpModules>
    <compilation debug="true"/>
    <pages/>
</system.web>

然后在vs里编译一下,就可以发现访问 http://site.com/xxxxxx.aspx  甚至  http://site.com/yyyy   都能输出了

但是,如果发布到iis7下去,又发现不工作了。

这时只要添加这一段到web.config,就可以了(不需要配置IIS7)(具体含义可以搜索单词)

1
2
3
4
5
6
<system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
        <add name="UrlRewriter" type="UrlRewrite.UrlRewrite,UrlRewrite"/>
    </modules>
    <validation validateIntegratedModeConfiguration="false"/>
</system.webServer>

如果是IIS6,则添加一个 “通配符应用程序映射”(或者实现为静态的.html等)

可执行文件从.aspx复制即可

去掉 确认文件是否存在的勾 就可以了

原文地址:https://www.cnblogs.com/cxd4321/p/3393266.html