localhost上的HttpWebRequest / Response(WebException:操作超时)

时间:2013-12-31 19:18:00

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

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

我正在使用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. 如何在localhost上测试HttpWebRequestHttpWebResponse
  3. 我尝试使用IP地址代替“localhost”,但这不起作用(ex 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);
            }
        }
    } 
    

1 个答案:

答案 0 :(得分:1)

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

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

相关问题