如果status!= 200,则HttpWebRequest返回null

时间:2018-03-12 08:51:37

标签: c# asp.net

我正在创建一个测试给定网址并获取状态代码的函数, 问题是HttpWebRequest变量将返回NULL - 如代码中所述 - 如果状态为tineOut或url无法达到,而它应该为timeOut返回 408

try
{
    request = (HttpWebRequest)WebRequest.Create(url); //set http request
    request.Timeout = timeOut * 1000;
    request.ContinueTimeout = timeOut * 1000;

    stopwatch.Start(); //start timer
    response = (HttpWebResponse)request.GetResponse(); //this will return NULL if URL is timedOut or not reachable
    response.Close(); //close session 
    stopwatch.Stop(); //Stop timer

    statusCode = (int)response.StatusCode; //save status code as int
    info[0] = stopwatch.Elapsed.TotalMilliseconds.ToString(); //store Latency to info
    info[1] = statusCode.ToString(); //store status code
    info[2] = response.StatusDescription; //store status description 
}
catch (WebException err) //catch timeOut case
{
    stopwatch.Stop();

    var responseObj = err.Response as HttpWebResponse; //err.Response is NULL as well.
    info[0] = stopwatch.Elapsed.TotalMilliseconds.ToString(); //store Latency to info
    info[1] = (int)responseObj.StatusCode + "";//store status code
    info[2] = responseObj.StatusDescription; //store status description 
}

最后,我无法将这两个解决方案应用于我当前的代码,而它们似乎与我的问题相同。
How to define a more aggressive timeout for HttpWebRequest?
Catching HttpWebRequest Timeout


如果需要澄清,请通知我。

1 个答案:

答案 0 :(得分:4)

request.GetResponse()返回您尝试与之通信的网络服务器的响应。

现在,当您有超时或错误的URL时,来自Web服务器的响应将为NULL,因为您还没有从该服务器获得任何信息。

您可以使用从WebException获取的状态来检测超时。

以下是http通信的常规catch块。请注意,您的408实际上不正确,任何其他与http无关的问题最终都会为-1。

catch (WebException wbEx)
{
    if (wbEx.Status == WebExceptionStatus.ProtocolError)
    {
        if (wbEx.Response is HttpWebResponse response)
        {
            returnStatusCode = (int) response.StatusCode;
        }
        else // should not happen
        {
            returnStatusCode = -1;
        }
    }
    else
    {
        if (wbEx.Status == WebExceptionStatus.Timeout)
        {
            returnStatusCode = 408; // now this is not right because this is CLIENT timeout.
        }
    }
}
catch
{
    returnStatusCode =  -1;
}