【问题标题】:Override Reading of HTTP Body with .net C# HTTPHandler使用 .net C# HTTPHandler 覆盖对 HTTP 正文的读取
【发布时间】:2012-09-05 09:50:34
【问题描述】:

使用 C# 我想控制从 POST 读取 HTTP 请求。主要是读取multipart/form-data 文件上传的流以跟踪从客户端接收到的流。

使用 ProcessRequest 或 Async BeginProcessRequest,正文已被 ASP.net / IIS 解析。

有没有办法通过 HTTPHandler 覆盖内置读取,或者我必须使用其他机制?

非常感谢

安迪

更新 - 根据要求添加了代码示例,尽管与实现 IHttpHandler 的普通类没有什么不同

public class MyHandler : IHttpHandler
{

    public bool IsReusable { get { return true; } }

    public void ProcessRequest(HttpContext context)
    {
        // The body has already been received by the server
        // at this point.  

        // I need a way to access the stream being passed 
        // from the Client directly, before the client starts 
        // to actually send the Body of the Request.

    }

}

【问题讨论】:

    标签: c# asp.net httprequest httphandler multipartform-data


    【解决方案1】:

    看来您可以通过 HttpModule 的 context.BeginRequest 事件捕获流。

    例如:

    public class Test : IHttpModule
    {
    
        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(onBeginRequest);
        }
    
    
        public void onBeginRequest(object sender, EventArgs e)
        {
            HttpContext context = (sender as HttpApplication).Context;
            if( context == nul ) { return; }
    
            if (context.Request.RawUrl.Contains("test-handler.ext"))
            {
                Logger.SysLog("onBeginRequest");
                TestRead(context);
            }
    
        }
    
        // Read the stream
        private static void TestRead(HttpContext context)
        {
            using (StreamReader reader = new StreamReader(context.Request.GetBufferlessInputStream()))
            {
                Logger.SysLog("Start Read");
                reader.ReadToEnd();
                Logger.SysLog("Read Completed");
            }
        }
    }
    

    真的,我试图避免使用 HttpModules,因为它们是针对每个 .net 请求进行处理的,所以我真的很想知道如何通过 HTTPHandler 来完成它。

    【讨论】:

      【解决方案2】:

      您绝对可以通过实现 IHttpHandler 来做到这一点。

      这个example 将帮助您入门。无需覆盖内置读数。
      您收到请求中的所有数据,并可以根据需要对其进行处理。

      【讨论】:

      • 我在该示例中看不到任何直接从客户端读取正文的参考。与任何其他 HttpHander 没有什么不同,InputStream 已经缓冲了POST 的主体。我想从客户端读取实际流,不允许 IIS / .Net 读取正文。
      猜你喜欢
      • 1970-01-01
      • 2014-04-02
      • 1970-01-01
      • 1970-01-01
      • 2015-12-15
      • 2010-09-10
      • 1970-01-01
      • 2011-02-14
      相关资源
      最近更新 更多