c# - 获取请求文本

标签 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,但我不明白如何......

如何在发送前获取网络请求的 header 和正文?

添加:我最终想要的是:

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

谢谢。

最佳答案

将这些添加到您的配置文件中,这将几乎转储所有通信(这将保存到 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

关于c# - 获取请求文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3900381/

相关文章:

c# - 应用名称的 wp8 应用商店本地化

c# - 在 ASP.NET MVC 项目中使用 Serilog

c# - 如何将暴露给 COM 互操作的 .NET 对象标记为单线程?

c# - 将字符串解析为 TimeSpan

c# - 识字 LINQ-to-XML : Best practice to deserialize attribute/value to structured variable/value pairs

c# - 在 C# 中返回 "Functional Interface"

C# 字典允许看似相同的键

c# - 从 View 向 Controller 发送数据时支持的类型

c# - 从 web.config 获取连接字符串以在 EF POCO 中使用?

c# - 序列化问题