如何查看 HttpWebRequest 类发送的原始 HTTP 请求? [英] How do I see the raw HTTP request that the HttpWebRequest class sends?

查看:75
本文介绍了如何查看 HttpWebRequest 类发送的原始 HTTP 请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道你们都会回答使用像 Fiddler 这样的调试代理服务器",但事情没那么简单.

I know you are all going to answer "use a debugging proxy server like Fiddler" but it's not that simple.

这是我的情况:我有一些代码在服务器上运行,在 ASP.NET 页面代码隐藏 (aspx.cs) 中,它(除其他外)建立到另一个的连接服务器,抓取一些东西,然后将其格式化并返回给浏览器.

Here's my situation: I have some code that runs on a server, in an ASP.NET page code-behind (aspx.cs), which (among other things) establishes a connection to another server, grabs some stuff, and then formats it and returns it to the browser.

问题是另一台服务器做错了事情,所以我希望能够将调试标志传递到页面中(通过查询字符串,例如 ?debug=true),以便它打印出完全原始的 HTTP 请求,它正在发送到另一台服务器,因此我可以看到到底出了什么问题.这段代码在几个地方运行,所以我希望能够在开发、暂存或生产中传递这个标志并只看到请求,而不必弄清楚生产服务器是否可以与某处存在的某个代理服务器通信等

The problem is that the other server is doing the wrong thing, and so I want to be able to pass a debugging flag into the page (via the query string, e.g. ?debug=true) so that it will print out the completely raw HTTP request that it is sending to the other server so I can see what the heck is wrong. This code is running in several places so I want to be able to just pass in this flag on dev, staging, or production and just see the request, without having to figure out whether the production servers can talk to some proxy server that exists somewhere, etc.

您会认为这样做很容易,对吗?所以我觉得我疯了或什么的,但我查看了 HttpWebRequest 及其父类 WebRequest 的参考,并且——什么也没有.没办法.你会认为微软会想到这一点.最接近的是,您可以访问标题"集合,但是当我尝试它时,它省略了一些非常重要的标题,例如内容长度"——所以它一定是在说谎"(我知道这是在说谎,因为我知道对于远程服务器返回 200 状态的事实——请求成功,它只是返回错误/不同/错误的数据)

You would think that it would be easy to do this, right? So I feel like I'm crazy or something but I looked at the reference for HttpWebRequest and its parent class WebRequest and -- nothing. No can do. You would think Microsoft would have thought of this. The closest thing is that you can access the "Headers" collection but when I tried it, it omitted some really important headers like "content length" -- so it must be "lying" to me (I know it's lying, because I know for a fact that the remote server is returning a 200 status -- the request is successful, it's just returning bad/different/wrong data)

这是要求的代码示例:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://www.whatever.com");
req.Method = ... whatever ...;
... other setup for the request ...
/* At this point we are about to send the request.
   What does the raw HTTP request look like? */
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

推荐答案

您可以使用 System.Net 跟踪机制来查看在线发送的原始 HTTP 请求.您还可以将自己的跟踪侦听器添加到进程中.

You can use System.Net tracing mechanism to see the raw HTTP requests sent on the wire. You can also add your own tracelistener to the process.

这篇关于如何查看 HttpWebRequest 类发送的原始 HTTP 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆