【发布时间】: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。
所以我想知道:
- 我的代码有问题吗? (见下文)
- 如何在本地主机上测试
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