天天看點

HttpHandler的一個應用,aspx站點僞裝為php站點

版權聲明: 本文由 一隻部落格 發表于 bloghome部落格

文章連結: https://www.bloghome.com.cn/user/cnn237111

很簡單的小應用,通過httphandler,把字尾名是.php的請求交給指定的Httphandler處理即可。

首先要做的是在web.config配置好。

<httpHandlers>

      <add  verb="*" path="*.php" type="FakePHP.JustFakeIt"/>

</httpHandlers>

httpHandlers結點是在system.web結點下的。

正常配置如上,verb指定是post還是get,path的作用類似于限制請求的路徑,比如上面,隻要請求是php字尾名的,才能由此httpHandler處理。

type就是指定處理該請求的dll子產品,或者類型。本例中就是FakePHP.JustFakeIt這個類,此類實作了IHttpHandler接口。該節點詳細說明參考

http://msdn.microsoft.com/en-us/library/aa903367(v=vs.71).aspx

剩下的事情,就是要實作這個處理請求,建立FakePHP.JustFakeIt這樣一個類型,然後編碼。

using System.Web;  using System.IO;  using System.Net;   namespace FakePHP  {      /// <summary>      /// JustFakeIt 的摘要說明      /// </summary>      public class JustFakeIt : IHttpHandler      {           public void Proce***equest(HttpContext context)          {              context.Response.ContentType = "TEXT/HTML";              string page = context.Request.Path;               WebRequest mywebReq;              WebResponse mywebResp;              StreamReader sr;              string strHTML;               mywebReq = WebRequest.Create(HttpContext.Current.Request.Url.OriginalString.Replace(context.Request.Path, "/default.aspx"));              mywebResp = mywebReq.GetResponse();              sr = new StreamReader(mywebResp.GetResponseStream());              strHTML = sr.ReadToEnd();               context.Response.Write(strHTML);          }           public bool IsReusable          {              get             {                  return false;              }          }      }  }