【问题标题】:HttpWebRequest/Response on localhost (WebException: operation timed out)本地主机上的 HttpWebRequest/Response(WebException:操作超时)
【发布时间】:2014-01-01 03:31:37
【问题描述】:

我需要检查一些 HTTP 标头,因此我使用 C# 的 HttpWebRequest 和 HttpWebResponse 类。

我正在使用 Visual Studio 2012 进行开发,并想在我的本地主机上测试请求和响应,以便我可以看到我正在处理什么样的标头(我在 Chrome 中使用 devtools,所以我可以在那里看到,但是我想确保我的代码返回正确的值)。当我简单地输入http://localhost:[Port]/ 时,它无法连接。

我可以看到它反复向服务器发出请求,最终我得到了异常WebException: The Operation has timed out。如果我添加request.KeepAlive = false',那么我会得到异常WebException: Unable to connect to the remote server。

所以我想知道:

  1. 我的代码有问题吗? (见下文)
  2. 如何在本地主机上测试HttpWebRequest 和HttpWebResponse?

我尝试使用 IP 地址代替“localhost”,但这不起作用(例如 http://127.0.0.1:[port]/)

代码:

   public class AuthorizationFilterAttribute : ActionFilterAttribute
   {
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        string url = "http://127.0.0.1:7792/";
        string responseString;

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        //request.KeepAlive = false;
        //request.AllowAutoRedirect = false;

        System.Diagnostics.Debug.Write(request);


        try
        {
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    responseString = reader.ReadToEnd();
                    System.Diagnostics.Debug.Write(responseString);
                }
            }
        }
        catch (Exception e)
        {
            System.Diagnostics.Debug.Write(e.Message);
            System.Diagnostics.Debug.Write(e.Source);
        }
    }
} 

【问题讨论】:

  • 您不会在 Chrome 开发工具中看到任何信息,因为请求是由应用程序而不是浏览器发出的。
  • @Marthijn 这很有道理。是否有某种工具或插件可以拦截从应用程序生成的标头信息?我希望我可以通过使用Debug.Write 来输出响应并查看VS2012 的输出窗口中发送的内容。
  • 只需在应用程序中设置断点,请参阅此问题以获取屏幕截图:stackoverflow.com/questions/2371835/…

标签: c# asp.net-mvc httpwebrequest httpwebresponse


【解决方案1】:

你试过Fiddler吗? Fiddler 将向您显示所有 HTTP 请求、所有标头、响应状态,以及不同的数据视图,如原始、十六进制、图像等、时间线视图、HTTPS 连接,几乎所有内容。

还有像 httpfox 这样的 Firefox 扩展。但我强烈建议你试试 Fiddler。

【讨论】:

  • 我没听说过这个名字。我得看看它。
  • Fiddler 似乎有点矫枉过正。我真的很想知道代码是否会成功连接到服务器,如果连接后,我是否能够读取标题信息并相应地执行逻辑...
  • Fiddler 能否告诉我为什么我的请求总是超时?
猜你喜欢
  • 1970-01-01
  • 2020-03-28
  • 1970-01-01
  • 2012-09-21
  • 1970-01-01
  • 2020-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多