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

本文关键字:错误 授权 获取 状态 网站 何忽略 webrequest | 更新日期: 2023-09-27 18:26:31

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

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

我建议试试这个:

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

WebException具有响应所需的所有信息。

当服务器关闭或无法访问时,会出现超时异常。我知道唯一的办法就是尝试/接球。

我确信大多数错误(401/404/501)都是这样,所以:不,你不能忽略(防止)异常,但你必须处理它们。它们是获取应用程序正在查找的大部分StatusCode的唯一方法。

简而言之,您需要检查myHttpWebResponse.StatusCode的状态代码并采取相应的行动。

参考样本代码:

public static void GetPage(String url) 
    {
        try 
          { 
                // Creates an HttpWebRequest for the specified URL. 
                HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url); 
                // Sends the HttpWebRequest and waits for a response.
                HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); 
                if (myHttpWebResponse.StatusCode == HttpStatusCode.OK)
                   Console.WriteLine("'r'nResponse Status Code is OK and StatusDescription is: {0}",
                                        myHttpWebResponse.StatusDescription);
                // Releases the resources of the response.
                myHttpWebResponse.Close(); 
            } 
        catch(WebException e) 
           {
                Console.WriteLine("'r'nWebException Raised. The following error occured : {0}",e.Status); 
           }
        catch(Exception e)
        {
            Console.WriteLine("'nThe following Exception was raised : {0}",e.Message);
        }
    }