【问题标题】:Get XML doc sent获取发送的 XML 文档
【发布时间】:2011-03-28 19:42:22
【问题描述】:

我有 2 个项目 - 1 个纯粹只是一个 .ashx 通用处理程序,另一个是一个向其发布 XML 文档的测试项目。如何获取已发布的 XML 文档?

客户端代码为(为简洁起见)

    string xmlToSend = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><APPLICATION>  <TRANSACTIONTYPE>12</TRANSACTIONTYPE></APPLICATION>";
    WebRequest webRequest = WebRequest.Create(new Uri("http://localhost:8022/handle.ashx"));
    webRequest.ContentType = "text/xml";
    webRequest.Method = "POST";
    byte[] bytes = Encoding.ASCII.GetBytes(xmlToSend);
    Stream os = null;
    webRequest.ContentLength = bytes.Length;
    os = webRequest.GetRequestStream();
    os.Write(bytes, 0, bytes.Length);
    os.Close();
    WebResponse webResponse = webRequest.GetResponse();
    //if (webResponse == null)
    //{ return null; }
    StreamReader sr = new StreamReader(webResponse.GetResponseStream());
    string sRet = "";
    sRet = sr.ReadToEnd().Trim();

接收码是

public void ProcessRequest(HttpContext context)
{
    // Well, not sure what to do here.  
    // context.Request.Params has a count of 48, but doesn't have the XML.
    // context.Request.Form has a count of 0

}

我知道我在这里遗漏了一些基本的东西。但我一辈子都想不通。

请不要建议使用 WCF,除非这是我要让它工作的唯一方法。我发现 WCF 很难起床,也很挑剔。

我什至无法让我的处理程序在断点处中断,但我知道它正在被调用(我已经多次更改它以返回日期、日期和时间,我输入的一些乱码字符串,所以我知道它正在被调用并且可以回复。)

【问题讨论】:

  • 只是想指出 WebRequest.Create 应该包含一个指向资源msdn.microsoft.com/en-us/library/bw00b1dc.aspx的uri
  • 完成,乔。虽然我觉得我被骗了,因为我只是使用了“new Uri”并将我的 url 作为构造函数传递给它。不知道它给了我什么,但嘿,它已经完成了。
  • @Matt:这不是一个有效的 URI。我确信代码会立即抛出异常。
  • 是的,您需要修复您的 uri,这几乎就是您将 xml 发送到的 url。例如,“yourserver.com/xmlhandler.ashx。我还发布了关于 ProcessRequest 部分的问题的答案。
  • 抱歉——这是一个复制和粘贴错误。原始字符串应该是“localhost:8022”——XML 作为第二个参数传递并在“byte[] bytes = Encoding.ASCII.GetBytes(parameters);”行中使用我试图缩小代码把这一切搞砸了。

标签: c# xml http-post


【解决方案1】:

context.Request.InputStream 包含您要查找的数据。

微软的例子:

System.IO.Stream str; String strmContents;
Int32 counter, strLen, strRead;
// Create a Stream object.
str = Request.InputStream;
// Find number of bytes in stream.
strLen = Convert.ToInt32(str.Length);
// Create a byte array.
byte[] strArr = new byte[strLen];
// Read stream into byte array.
strRead = str.Read(strArr, 0, strLen);

// Convert byte array to a text string.
strmContents = "";
for (counter = 0; counter < strLen; counter++)
{
    strmContents = strmContents + strArr[counter].ToString();            
}

在处理文本时还有其他更好的方法,例如 StreamReader 或使用 StringBuilder 进行连接。

【讨论】:

  • 优秀。感谢你的回答。我将它(根据您的建议)缩短为: System.IO.Stream input;字符串内容;输入 = 上下文.Request.InputStream; System.IO.StreamReader reader = new StreamReader(input);内容 = reader.ReadToEnd();
【解决方案2】:
public void ProcessRequest(HttpContext context)
{
   string data = new StreamReader(context.Request.InputStream).ReadToEnd();
}

【讨论】:

  • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-19
  • 2020-12-30
  • 1970-01-01
  • 1970-01-01
  • 2019-12-28
相关资源
最近更新 更多