我正在编写一个端口扫描器来检测在本地网络上运行的 Web 服务。其中一些 Web 服务需要基本身份验证 - 我不知道这些服务的用户名/密码,我只想列出它们,所以我无法在这个阶段提供凭据。我正在使用代码:
var request = (HttpWebRequest)WebRequest.Create("http://" + req);
request.Referer = "";
request.Timeout = 3000;
request.UserAgent = "Mozilla/5.0";
request.AllowAutoRedirect = false;
request.Method = WebRequestMethods.Http.Head;
HttpWebResponse response = null;
try
{
response = (HttpWebResponse) request.GetResponse();
// I want to parse the headers here for the server name but as the exception is thrown the response object is null.
}
catch (Exception ex)
{
//401 error is caught here - response is null
}
然后我从返回的 header 中解析出服务器名称 - 我知道它们正在返回,因为我可以用 fiddler 看到它们但是 HttpWebResponse 对象设置为 null 因为 GetResponse() 方法抛出异常.基本上 - 我如何让它不抛出异常但返回 header 以及状态代码 401。
最佳答案
如果您捕获到 WebException
,您将有权访问 ex.Response
,并且您可以从那里检索您的 header 。
关于c# - 如何从 401 服务器错误中获取 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9074707/