c# - 如何忽略来自 webrequest 的 401 未授权错误以获取网站状态

标签 c# .net httpwebrequest

我正在编写一个应用程序来检查一些内部网络应用程序的状态。其中一些应用程序使用 Windows 身份验证。当我使用此代码检查状态时,它抛出 The remote server returned an error: (401) Unauthorized.。这是可以理解的,因为我没有向网站提供任何凭据,所以我没有获得授权。

WebResponse objResponse = null;
WebRequest objRequest = HttpWebRequest.Create(website);
objResponse = objRequest.GetResponse();


有没有办法在不执行类似操作的情况下忽略 401 错误?

WebRequest objRequest = HttpWebRequest.Create(website);

try
{
    objResponse = objRequest.GetResponse();
}
catch (WebException ex)
{
    //Catch and ignore 401 Unauthorized errors because this means the site is up, the app just doesn't have authorization to use it.
    if (!ex.Message.Contains("The remote server returned an error: (401) Unauthorized."))
    {
        throw;
    }                    
}

最佳答案

我建议试试这个:

        try
        {
            objResponse = objRequest.GetResponse() as HttpWebResponse;
        }
        catch (WebException ex)
        {
            objResponse = ex.Response as HttpWebResponse;
        }
        finally

WebException 具有您想要的所有信息的响应。

关于c# - 如何忽略来自 webrequest 的 401 未授权错误以获取网站状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9517409/

相关文章:

c# - "for(;;)"在 C# 中有什么作用?

c# - 正则表达式 .NET 问题

c# - 在 C# 中使用 enum 和 struct 代替 switch 语句

c# - 我可以在 C# 中加载应用程序期间捕获丢失的 dll 错误吗?

c# - 如何以编程方式检索 html 重定向网页?

c# - Discord 添加公会成员 401 错误尽管显然有效的访问 token

c# - 使用 LockBits 从内存创建的 GDI+ 通用错误保存位图

C# Cookie - Expires 属性不会设置

c# - 将 C# 三元与 String.Equals 一起使用

c# - 在 C# 可移植类库 (Microsoft.Net.Http) 中使用代理