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

原文地址:https://www.cnblogs.com/PerfectSoft/p/4214691.html