在Asp.Net裡使用自訂映射進行重新導向

來源:互聯網
上載者:User
  在IIS網站屬性中添加自訂映射,如添加一個副檔名為.fbsx的檔案類型,通過實現IHttpHandler來進行重新導向。

  實現IHttpHandler的類:

 1using System;
 2using System.Text.RegularExpressions;
 3using System.Web;
 4using System.Web.SessionState;
 5
 6namespace FaibClass.Common.Web
 7{
 8    public class URLRewriterHandler : IHttpHandler, IRequiresSessionState
 9    {
10        public void ProcessRequest(HttpContext context)
11        {
12            URLRewriterRuleCollection rules = URLRewriterConfiguration.GetConfig().Rules;
13            string requestedPath = context.Request.FilePath;
14            for(int i = 0; i < rules.Count; i++)
15            {
16                Regex reg = new Regex(rules[i].MatchUrl, RegexOptions.IgnoreCase);
17                bool isMatch = reg.IsMatch(requestedPath);
18                if(isMatch)
19                {
20                    context.Server.Execute(reg.Replace(requestedPath, rules[i].RedirectUrl));
21                }
22            }
23        }
24
25        public bool IsReusable
26        {
27            get
28            {
29                return true;
30            }
31        }
32    }
33}

  使用IRequiresSessionState的目的是:能夠在目標頁面中使用Session。注意如果目標頁面中使用Ajax.Net組件,在註冊類型的時候應使用第二個參數:
AjaxPro.Utility.RegisterTypeForAjax(typeof(YourClass), this);

  開啟IIS管理器,在網站屬性的映射中添加一個.fbsx的副檔名,其他設定與.aspx的一致,注意“確認檔案是否存在”不能勾選。

  在web.config中配置httpHandlers節:1 <httpHandlers>
2   <add verb="POST,GET" path="*.fbsx" type="FaibClass.Common.Web.URLRewriterHandler, FaibClass.Common" />
3 </httpHandlers>

  並配置重新導向配置節 <configSections>
   <section name="URLRewriterConfig" type="FaibClass.Common.Web.URLRewriterConfigSerializerSectionHandler, FaibClass.Common" />
  </configSections>
  <URLRewriterConfig>
    <Rules>
       <URLRewriterRule>
         <MatchUrl>([\d]+)\.fbsx</MatchUrl>
         <RedirectUrl><![CDATA[target.aspx?to=$1]]></RedirectUrl>
       </URLRewriterRule>
     </Rules>
  </URLRewriterConfig>

  這樣,只要我們鍵入一個1234.fbsx檔案,瀏覽器就會重新導向到target.aspx頁面進行相應的執行。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.