2014-10-30 80 views
2

這應該是如此簡單,我覺得我只是想念一些東西。我對這個應用程序的HTTP方面很陌生,所以我也覺得我在黑暗中拍攝。通過C#訪問多部分HTTP請求正文IHttpHandler

我們正在做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;上設置的斷點。

我錯過了什麼?

+0

是什麼類型'Files'?它是否可以顯式轉換爲'XmlDocument'? – 2014-10-30 16:55:47

+0

'文件'的類型爲'HttpFileCollection'。我確定它不能轉換爲'XmlDocument'。這只是現在的探索性代碼。 – 2014-10-30 17:08:25

回答

2

您需要使用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); 
} 
+0

哦,我的天啊!我期待着指出答案,而不是答案本身。非常感謝!這需要更改方法簽名,返回XDocument而不是XmlDocument。但我會接受! – 2014-10-30 20:09:23

+0

@Jeff你總是可以創建一個'XmlDocument'實例並將流傳遞給'Load'方法。 – 2014-10-30 21:04:18