您的位置:首页 > 其它

URL重写

2015-10-05 13:32 211 查看
1》

第一种是在Global.asax中实现 或者在HttpModel里实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Text.RegularExpressions;

namespace WebApp
{
public class Global : System.Web.HttpApplication
{

protected void Application_Start(object sender, EventArgs e)
{

}

protected void Session_Start(object sender, EventArgs e)
{

}

protected void Application_BeginRequest(object sender, EventArgs e)
{
//获取当前请求原始url
string url = Request.RawUrl;

//定义一个正则表达式
Regex reg = new Regex("/WebForm1/(.*)/(.*)");

//判断用户输入的url是否满足正则表达式
bool b = reg.IsMatch(url);

if (b)
{
//假如用户输入的是:http://localhost:6298/WebForm1/1/zhangshan
//那么在这里需要将它替换成一个正常的URL。然后得到一个新的正常URL
string newUrl = reg.Replace(url, "/WebForm1.aspx?Id=$1&name=$2");

//将新的url赋值给原始的url
//Request.RawUrl = newUrl;//不能这样写,因为RawUrl这个属性的访问界别是不public而是internal,它只有在程序集内部设值(访问),而这里我们是引用的微软的System.Text.RegularExpressions类库,他们不只同一个程序集中。所以无法这样设值。

//我们应该使用RewritePath方法来实现:RewritePath方法是:使用给定路径重写 URL。
Context.RewritePath(newUrl);
}

}

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{

}

protected void Application_Error(object sender, EventArgs e)
{

}

protected void Session_End(object sender, EventArgs e)
{

}

protected void Application_End(object sender, EventArgs e)
{

}
}
}


第二种是在IIS中的 url重写模块中实现 (这种方式是要在一个网站已经发布后并且已经部署到IIS中来实现)

首先呢,如果你IIS中没有  URL重写 模块。那么我们需要下载一个 Web平台安装程序 Microsoft Web Platform Installer 5.0

X86下载地址  X64下载地址

下载完毕后安装,安装完毕后在搜索框中搜索 URL重写工具 或者直接搜索URL。 然后找到URL重写工具2.0 ,然后再安装那里点击一下“添加” 其实就是安装的意思。



安装好“URL重写” 模块以后我们再打开IIS 会发现里面多了一个“IIS重写” 模块



然后我们打开URL重写模块,添加规则



然后> WebForm1.aspx?id=1 &name=zhangshan  这id=1的1 和name=zhangshan的zhangshan是参数,可以随便写 只要符合我们的规则就行了。



点击确定。URL重写就搞定了


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: