ASP.NET HttpHandler使用總結

  在網絡開發中,基本上任何項目都會涉及到一些xml配置文件,用來存放一些敏感數據,通過這些文件都是不允許客戶端瀏覽的,那麼如何禁止用戶瀏覽?直接對有關xml文件的請求做特殊處理即可。在ASP.NET中,HttpHandler用來處理特定類型的請求。HttpHandler定義如下:

public interface IHttpHandler
    {
        // Summary:
        //     Gets a value indicating whether another request can use the System.Web.IHttpHandler
        //     instance.
        //
        // Returns:
        //     true if the System.Web.IHttpHandler instance is reusable; otherwise, false.
        bool IsReusable { get; }

        // Summary:
        //     Enables processing of HTTP Web requests by a custom HttpHandler that implements
        //     the System.Web.IHttpHandler interface.
        //
        // Parameters:
        //   context:
        //     An System.Web.HttpContext object that provides references to the intrinsic
        //     server objects (for example, Request, Response, Session, and Server) used
        //     to service HTTP requests.
        void ProcessRequest(HttpContext context);
    }

  以接口的形式定義,所以自定義類只要實現該接口,即可對特定類型的請求進行特殊處理。就以禁止下載xml文件爲例,演示如何使用IHttpHandler。

  定義一個CustomHandler類,實現IHttpHandler接口

namespace AspNet.HttpHandler.HttpHandler
{
    public class CustomHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            //獲取文件擴展名
            string fileExtension = Path.GetExtension(context.Request.RawUrl);
            if (fileExtension.Equals(".xml"))
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write("File not found");
            }
        }
    }
}

  現在在Web.config文件中對CustomHandler進行在IIS7中的配置:

<system.webServer>
  <handlers>
      <add name="CustomHandler" path="*.xml" verb="GET" type="AspNet.HttpHandler.HttpHandler.CustomHandler"/>
  </handlers>
</system.webServer>

  path:代表處理的請求類型,以後是處理所有的xml文件請求

  verb:代表請求的方式,如:GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS

  type:處理這些請求的HttpHandler

 

  在IIS6中配置如下:

<system.web>
  <httpHandlers>
      <add path="*.xml" verb="GET" type="AspNet.HttpHandler.HttpHandler.CustomHandler"/>
  </httpHandlers>
</system.web>

  現在如果再請求xml文件,得到的返回結果是:File not found

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章