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

时间:2012-03-01 13:52:35

标签: c# .net httpwebrequest

我正在编写一个应用程序来检查一些内部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;
    }                    
}

3 个答案:

答案 0 :(得分:18)

我建议试试这个:

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

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

答案 1 :(得分:3)

当服务器关闭或无法访问时,您将收到超时异常。我知道处理它的唯一方法是使用try / catch。

我很确定大多数错误都是这种情况(401/404/501),所以:不,你不能忽视(阻止)异常,但你必须处理它们。它们是获取App正在寻找的大多数StatusCodes的唯一方法。

答案 2 :(得分:2)

缺点是,您需要检查myHttpWebResponse.StatusCode状态代码并采取相应措施。

来自reference的示例代码:

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);
        }
    }