URL重写

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重写就搞定了




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值