Asp.net 实现URL重写 测试通过(原创)

来源:互联网 发布:怎么找淘宝商家接单 编辑:程序博客网 时间:2024/06/05 17:18

使用HttpModule实现URL重写的方法使你不用修改aspx页面的任何内容,HttpModule支持正则表达式,不过在使用前要把Intelligencia.UrlRewriter.dll这个DLL文件放到你的bin目录下。

这有几个你现在就可以下载和使用的免费的HttpModule:

  • UrlRewriter.net
  • UrlRewriting.net

这些模块允许你用声明的方式在你应用的web.config文件里表达匹配规则。

说了那么多,现在开始操作吧!!!

关键的是修改web.config的内容,在web.config页面中添加下面的内容:

<system.web>
  <httpModules>
   
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter"/>
  </httpModules>
  <compilation debug="true"/>
  </system.web>
 
<rewriter>
  <rewrite url="~/Products?(g=)?(.+)" to="~/Products.aspx?g=$2"/> <!--这里的(g=)?是我测试的时候恰巧测试成功的,不过第一个参数要经过SubString方法处理,原因不清楚-->
 </rewriter>

Default.aspx页面的内容:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>Ecommerce Demo</h1>
       
        <p>Pick one of the links below to see products by category:</p>
       
        <ul>
           
<li><a href="Products?g=Books&id=1&t=Books">Books</a></li>
            <li><a href="Products?g=DVDs&id=2&t=DVDs">DVDs</a></li>
            <li><a href="Products?g=CDs&id=3&t=CDs">CDs</a></li>
  
        </ul>
       
    </div>
    </form>
</body>
</html>

参数接受页面Products.aspx:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Products.aspx.vb" Inherits="Products" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>
            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        </h1>
       
        <p>Todo: List books here...</p>  
       
    </div>
    </form>
</body>
</html>

Product.aspx.cs代码:
Partial Class Products
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Label1.Text = "Category: " & Request.QueryString("g").Substring(3) & " " & Request.QueryString("id") & " " & Request.QueryString("t")

    End Sub

End Class

我做了一个现成的例子,需要的请点击这里链接下载

原创粉丝点击