我试图从HttpWebRequest返回的HttpWebResponse对象中获取HTTP状态码号码。我希望得到实际的数字(200,301,302,404等),而不是文本描述。(“Ok”,“movedpermanent”等)数字是否被埋在响应对象的某个属性中?除了创建一个大型开关函数,还有什么其他想法吗?谢谢。

HttpWebRequest webRequest = (HttpWebRequest)WebRequest
                                           .Create("http://www.gooogle.com/");
webRequest.AllowAutoRedirect = false;
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
//Returns "MovedPermanently", not 301 which is what I want.
Console.Write(response.StatusCode.ToString());

当前回答

只需将StatusCode强制转换为int。

var statusNumber;
try {
   response = (HttpWebResponse)request.GetResponse();
   // This will have statii from 200 to 30x
   statusNumber = (int)response.StatusCode;
}
catch (WebException we) {
    // Statii 400 to 50x will be here
    statusNumber = (int)we.Response.StatusCode;
}

其他回答

//Response being your httpwebresponse
Dim str_StatusCode as String = CInt(Response.StatusCode)
Console.Writeline(str_StatusCode)

根据'dtb',你需要使用HttpStatusCode,但遵循'zeldi',你需要格外小心的代码响应>= 400。

这对我来说很有效:

HttpWebResponse response = null;
HttpStatusCode statusCode;
try
{
    response = (HttpWebResponse)request.GetResponse();
}
catch (WebException we)
{
    response = (HttpWebResponse)we.Response;
}

statusCode = response.StatusCode;
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
sResponse = reader.ReadToEnd();
Console.WriteLine(sResponse);
Console.WriteLine("Response Code: " + (int)statusCode + " - " + statusCode.ToString());

下面是我处理这种情况的方法。

//string details = ...
//...
catch (WebException ex)
{
    HttpStatusCode statusCode = ((HttpWebResponse)ex.Response).StatusCode;
    if (statusCode == HttpStatusCode.Unauthorized)
    {
        Reconnect();
        //...
    }
    else if (statusCode == HttpStatusCode.NotFound)
    {
        FileLogger.AppendToLog("[ERROR] Not Found: " + details);
    }
    else
    {
        FileLogger.AppendToLog("[ERROR] " + ex.Message + ": " + details);
    }
}

您必须小心,在4xx和5xx范围内的服务器响应将抛出webeexception。你需要捕获它,然后从WebException对象获取状态代码:

try
{
    wResp = (HttpWebResponse)wReq.GetResponse();
    wRespStatusCode = wResp.StatusCode;
}
catch (WebException we)
{
    wRespStatusCode = ((HttpWebResponse)we.Response).StatusCode;
}
Console.Write((int)response.StatusCode);

HttpStatusCode (response.StatusCode的类型)是一个枚举,其中成员的值与HTTP状态码匹配。

public enum HttpStatusCode
{
    ...
    Moved = 301,
    OK = 200,
    Redirect = 302,
    ...
}