zoukankan      html  css  js  c++  java
  • 在 ASP.NET 中执行 URL 重写

    microsoft原地址:

    简单实用的重写URL(URLRewriter.dll),URLrewriter.dll可以微软官方网站下载,比较旧的东西了
    大概记录一下实现的方法
    修改web.cofing
    在<configuration>节点内加入引用程序集


        <section name="RewriterConfig" type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter" />
      </configSections>

    重写URL

      <RewriterConfig>
        <Rules>
            <!--重写按年查询地址-->
            <RewriterRule>
                <LookFor>~/content_list_year,(\d{1,9}),(\d{1,9}),(\d{4})\.aspx</LookFor>
                <SendTo><![CDATA[~/Test.aspx?bigtypeid=$1&smalltypeid=$2&postyear=$3]]></SendTo>
            </RewriterRule>
            <!--重写评论地址-->
            <RewriterRule>
                <LookFor>~/comment,(\d{1,9})\.aspx</LookFor>
                <SendTo><![CDATA[~/comment.aspx?PostID=$1]]></SendTo>
            </RewriterRule>

        </Rules>
      </RewriterConfig>

    (注:重写的URL要以aspx结尾,如想输入目录达到URL重写要在目录下创建一个default.aspx(IIS中的默认档))

    我说的可能不是很详细,看微软提供的代码吧)

    http://www.microsoft.com/china/msdn/library/webservices/asp.net/URLRewriting.mspx


    ==========================

    asp.net URL重写(URLRewriter) 之简化版

    ===============================

    asp.net 2.0 简单实现url重写
    今天,群里有人问我关于Url重写的问题,想这重写,记得国庆期间看过相关文章,msdn介绍也看过,大概就三种方法,最常用的就是用微软提供的dll文件,今天,把我dll引用了一下,按着说明配置了一下文件,结果出现不少问题,调试时找不到.cs源代码,不知是啥问题,可能dll放的太久,生秀了..-_-.#,只好上网再搜一下新的dll,突然发现2.0里的新方法!花了半个晚上做一个demo!
    以下是demo源代码:  项目里只有两个页面(Default.aspx,user.aspx(直接response.write(request.querystring["userId"]))
    protected void Application_BeginRequest(object sender, EventArgs e)
        {
            string suffixUrl, lastUrl, newurl = string.Empty, userId = string.Empty ;
            lastUrl = Request.RawUrl;
            if (lastUrl.Substring(0, 11).ToLower() == "/urlrewrite")//"urlrewirte是根目录名,加判断的原因是本地测试时
             {                                                                //被取出来,上传到服务器时根目录会被域名取代(消失)!
                suffixUrl = lastUrl.Substring(12).ToLower();
            }
            else
            {
                suffixUrl = lastUrl.Substring(1).ToLower();
            }
            bool isMatch = false;
            Regex myReg = new Regex(@"user/([\w\d]+)\.aspx");
            if (myReg.IsMatch(suffixUrl))
            {
                isMatch = true;
                int first=suffixUrl.LastIndexOf('/')+1;
                int end=suffixUrl.LastIndexOf('.');
                int lenght=end-first;
                userId=suffixUrl.Substring(first,lenght);//获取被匹配的组部分
            }
            if (isMatch)
            {
               newurl="~/user.aspx?userId="+userId;
             }
            else
              {
                newurl = "~/Default.aspx";
               }
     
            HttpContext.Current.RewritePath(newurl); //最关键的一句话,重写Url
        }
    测试输入:http://xxx/urlrewrite/usre/cyq1162.aspx(地址栏显示)
    成功定向到:http://xxx/urlrewrite/user.aspx?userid=cyq1162(页面内容显示)
    ..很简单吧..不用引入dll,也不用配置Webconfig.轻松的几行代码搞定!

    ============================

    httpHandle,及httpModles及httpApplication是asp.net的三个自定义处理模块,I

    IhttpMododule实现类

    FormsAuthenticationModule  AuthenticateRequest  确定用户是否通过了窗体身份验证。如果没有,用户将被自动重定向到指定的登录页面。
    FileAuthorizationMoudle    AuthorizeRequest           使用 Windows 身份验证时,此 HTTP 模块将检查以确保 Microsoft® Windows® 帐户对被请求                                                                             的资源具有足够的权限。
    UrlAuthorizationModule  AuthorizeRequest              检查以确保请求者可以访问指定的 URL。通过 Web.config 文件中的 <authorization> 和  <location> 元素来指定 URL 授权。


     

    图 2. IIS 和 ASP.NET 正在处理请求

    在 asp.net 里实现 URL重写(URLRewriter)的一个最简单的方法。

    参考了 (作者 Scott Mitchell 翻译:Janssen )的大作,虽然没有完全看明白,但是也照猫画虎地做了一个,颇有“成就”感。写出来分享一下。

    原作里讲了很多的原理,这里就不说了(其实我也不懂)。这里就写操作过程吧。目的是实现一个最简单的能实现 URL重写 的程序。

    1、需要设置一下IIS里的站点属性。

    2、修改web.config的内容。

     <system.web>
          <httpHandlers>
            <add verb="*" path="*.zhtml" type="ZDIL.URLRewriter.RewriterFactoryHandler, ZDILURLRewriter" />
        </httpHandlers>
    </system.web>
        其中*.zhtml 就是地址栏里面写的网页的扩展名,就是给用户看的,这个可以随意改(但是要符合扩展名的规则!)。当然要和第一步里面的设置相一致才行。

    3、写一个类。

    using System;
    using System.IO;
    using System.Web;
    using System.Web.UI;

    namespace ZDIL.URLRewriter
    {
        /**//// <summary>
        /// URL重写
        /// </summary>
        public class RewriterFactoryHandler : IHttpHandlerFactory
        {
            /**//// <summary>
            /// GetHandler is executed by the ASP.NET pipeline after the associated HttpModules have run.  The job of
            /// GetHandler is to return an instance of an HttpHandler that can process the page.
            /// </summary>
            /// <param name="context">The HttpContext for this request.</param>
            /// <param name="requestType">The HTTP data transfer method (<b>GET</b> or <b>POST</b>)</param>
            /// <param name="url">The RawUrl of the requested resource.</param>
            /// <param name="pathTranslated">The physical path to the requested resource.</param>
            /// <returns>An instance that implements IHttpHandler; specifically, an HttpHandler instance returned
            /// by the <b>PageParser</b> class, which is the same class that the default ASP.NET PageHandlerFactory delegates
            /// to.</returns>
            public virtual IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
            {
                string sendToUrl = url;                         //地址栏里面的地址
                string filePath = pathTranslated;

                string sendToURLString = "/web/index.aspx";  //真正要访问的页面
                string queryString = "";                     //参数。比如 ?id=123

                filePath = context.Server.MapPath(sendToURLString); //物理地址

                //这句最重要了。转向了。
                context.RewritePath(sendToURLString, String.Empty, queryString);
               
                //这个还没有弄明白 :)
                return PageParser.GetCompiledPageInstance(url, filePath, context);
            }

            public virtual void ReleaseHandler(IHttpHandler handler)
            { //这个也不懂了
            }
        }
    }
     

    这个类呢,要写在一个单独的项目里面,然后编译成 ZDILURLRewriter.DLL文件。(注意文件名,写错了就不能正常运行了)。

    4、完成了。

    打开IE ,在地址栏里输入 http://.../1.zhtml

    浏览者看到是一个静态页的地址,但是实际上访问的却是 /web/index.aspx 这个动态网页。


    怎么样简单吧。

    当然了,这个是最简单的,简单到了“不能用”的地步了。因为他会把所有的 *.zhtml 的访问都“重写”到 /web/index.aspx 。

    至于把什么样的网页重写到哪个网页,这里就不介绍了(这里只讲方法,不讲实现的细节)。

    方法很多了,原作是通过正则来匹配的,我是通过 string sendToUrl = url; 来判断的。

    其他的就看你们的需要了。

    http://blog.csdn.net/shixin1198/archive/2006/10/16/1336846.aspx

    本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/cxzhq2002/archive/2007/05/10/1603265.aspx

  • 相关阅读:
    密码数学大作业
    《数据结构》教材测评
    机器学习概述
    SQL基础-流程控制结构
    SQL基础-变量 存储过程和函数
    SQL基础-视图
    SQL基础-TCL 事务控制语言
    SQL基础-DDL 数据定义语言
    SQL基础-DML 数据操作语言
    SQL基础 -DQL 数据查询语言(下)
  • 原文地址:https://www.cnblogs.com/sntetwt/p/2034435.html
Copyright © 2011-2022 走看看