我正在编写一个应用程序来检查一些内部网络应用程序的状态。其中一些应用程序使用 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/