ASP.NET HttpHandler使用总结

  在网络开发中,基本上任何项目都会涉及到一些xml配置文件,用来存放一些敏感数据,经过这些文件都是不容许客户端浏览的,那么如何禁止用户浏览?直接对有关xml文件的请求作特殊处理便可。在ASP.NET中,HttpHandler用来处理特定类型的请求。HttpHandler定义以下:web

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接口ide

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中的配置:spa

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

  path:表明处理的请求类型,之后是处理全部的xml文件请求code

  verb:表明请求的方式,如:GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONSserver

  type:处理这些请求的HttpHandlerxml

 

  在IIS6中配置以下:blog

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

  如今若是再请求xml文件,获得的返回结果是:File not found接口

相关文章
相关标签/搜索