获取请求文本

时间:2010-10-10 12:57:26

标签: c#

我有HttpWebRequest

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(methodUrl.ToString());
req.Method = "POST";
string postData = Serializer.Serialize(GetAllFields());
req.ContentType = @"application/json; charset=utf-8";
req.Accept = @"application/json; charset=utf-8";  
...

我希望在发送之前看到实际的原始请求 (req.ToString()仅提供req的类型)
我得出结论我应该以某种方式使用Stream,但我无法理解如何......

如何在发送之前获取我的网络请求标题和正文?

已添加:我最终想要的是:

string requestAsText= //some method that will give me the whole post text.

感谢。

1 个答案:

答案 0 :(得分:2)

将这些添加到您的配置文件中,这将几乎转储每个通信(这保存到network.log文件):

<system.diagnostics>
    <sources>
      <source name="System.Net" tracemode="includehex" maxdatasize="1024">
        <listeners>
          <add name="System.Net"/>
        </listeners>
      </source>
      <source name="System.Net.Sockets">
        <listeners>
          <add name="System.Net"/>
        </listeners>
      </source>
      <source name="System.Net.Cache">
        <listeners>
          <add name="System.Net"/>
        </listeners>
      </source>
    </sources>
    <switches>
      <add name="System.Net" value="Verbose"/>
      <add name="System.Net.Sockets" value="Verbose"/>
      <add name="System.Net.Cache" value="Verbose"/>
    </switches>
    <sharedListeners>
      <add name="System.Net"
        type="System.Diagnostics.TextWriterTraceListener"
        initializeData="network.log"
      />
    </sharedListeners>
    <trace autoflush="true"/>
  </system.diagnostics>

http://msdn.microsoft.com/en-us/library/ty48b824.aspx