【问题标题】:Accessing Multipart HTTP Request Body via C# IHttpHandler通过 C# IHttpHandler 访问多部分 HTTP 请求正文
【发布时间】:2014-10-30 16:27:34
【问题描述】:

这应该很简单,我觉得我只是错过了一些东西。我是这个应用程序的 HTTP 方面的新手,所以我也觉得我在黑暗中拍摄。

我们正在做 B2B EDI。我们将收到一个多部分的 POST 请求。每个部分都是 XML。我需要提取每个部分并将每个部分转换为 XmlDocument。

这是我写的。

using System;
using System.Collections.Generic;
using System.Web;
using System.Xml;

namespace Acme.B2B
{
    public class MultipleAttachments : IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable { get { return true; } }

        public void ProcessRequest(HttpContext context)
        {
            var ds = extractDocuments(context.Request);

            return; // Written for debugging only.
        }

        #endregion

        #region Helper Members

        private IEnumerable<XmlDocument> extractDocuments(HttpRequest r)
        {
            // These are here for debugging only.
            var n = r.ContentLength;
            var t = r.ContentType;
            var e = r.ContentEncoding;

            foreach (var f in r.Files)
                yield return (XmlDocument)f;
        }

        #endregion
    }
}

我非常有信心 (XmlDocument)f 不会工作,但我仍在探索。奇怪的是,在var n = r.ContentLength; 上设置了一个断点,代码永远不会到达那个断点。它刚刚达到了我在无关的return; 上设置的断点。

我到底错过了什么?

【问题讨论】:

  • Files 是什么类型?是否可以显式转换为XmlDocument
  • Files 的类型为 HttpFileCollection。我确定它不能转换为XmlDocument。这只是现在的探索性代码。

标签: c# .net http multipart ihttphandler


【解决方案1】:

您需要使用HttpPostedFile.InputStream 并将其传递给XDocument 构造函数:

foreach (HttpPostedFile postedFile in r.Files)
{
    yield return XDocument.Load(postedFile.InputStream);
}

或者如果你想要XmlDocument:

foreach (HttpPostedFile postedFile in r.Files)
{
    yield return new XmlDocument().Load(postedFile.InputStream);
}

【讨论】:

  • 天哪!我期待的是指向答案的指针,而不是答案本身。非常感谢!这需要更改方法签名,返回 XDocument 而不是 XmlDocument。但我会接受的!
  • @Jeff 你总是可以创建XmlDocument 的实例并将流传递给Load 方法。
猜你喜欢
  • 2017-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-28
  • 2013-04-06
  • 1970-01-01
相关资源
最近更新 更多