c# - 如何从 401 服务器错误中获取 header

标签 c# .net httpwebrequest

我正在编写一个端口扫描器来检测在本地网络上运行的 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/

相关文章:

带有 post 的 C# HTTPS 请求

c# - 如何在 Http 响应完成之前读取响应流

c# - HttpWebRequest.BeginGetResponse block 30-60 秒

c# - 在 C# 中将三个元素存储在一个变量中

c# - 为什么 Entity Framework 返回 null List<> 而不是空列表?

c# - 有没有一种简单的方法可以将(lambda 表达式)字符串解析为 Action 委托(delegate)?

c# - 从实异常(exception)部将属性设置为 null

.net - 从字符串中拆分整数

c# - Automapper 在第一次调用时正确映射,但在第二次调用时跳过属性

c# - 比较版本标识符