HttpStatusCode是指任何500类型的状态码。

13

我想知道是否有一种更简单(更好的)方法来检查500状态码?

我能想到的唯一方法是这样做:

var statusCodes = new List<HttpStatusCode>()
{
  HttpStatusCode.BadGateway,
  HttpStatusCode.GatewayTimeout,
  HttpStatusCode.HttpVersionNotSupported,
  HttpStatusCode.InternalServerError,
  HttpStatusCode.NotImplemented,
  HttpStatusCode.ServiceUnavailable
};
if (statusCodes.Contains(response.StatusCode))
{
  throw new HttpRequestException("Blah");
}

我注意到这些是500种类型:

  • BadGateway
  • GatewayTimeout
  • HttpVersionNotSupported
  • InternalServerError
  • NotImplemented
  • ServiceUnavailable

5
你可以检查数值范围为500..599。 - Thilo
巴,我没意识到它们是可转换的 :$ - Dr Schizo
1个回答

14

以5xx开头的状态码表示服务器错误,因此简单的方法是:

if ((int)response.StatusCode>=500 && (int)response.StatusCode<600)
      throw new HttpRequestException("Server error");

1
奖金:bool success = ((int)response.StatusCode) >= 200 && ((int)response.StatusCode) < 300; - Alain
1
为避免使用魔数,请使用以下代码:(int)response.StatusCode >= (int)System.Net.HttpStatusCode.InternalServerError - Richard Ev
4
为什么不直接写成response.StatusCode >= HttpStatusCode.InternalServerError - c24w

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接