我们正在编写一组类似服务的REST,我们将错误作为不同的StatusCode返回。
在我们的客户端应用程序中,如果我们的工作流程不需要我们捕获并转换异常以发现错误代码,我们就更喜欢。
有没有办法告诉WebClient或HttpWebRequest在遇到200以外的StatusCode时停止抛出异常?
答案 0 :(得分:2)
没有。设计说除了200或201以外的任何东西都是特殊的。
HttpStatusCode httpStatusCode;
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://example.org/resource");
try
{
using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
// handle 200/201 case
}
}
catch (WebException webException)
{
if (webException.Response != null)
{
HttpWebResponse httpWebExceptionResponse = (HttpWebResponse)webException.Response;
switch (httpWebExceptionResponse.StatusCode)
{
case 304: // HttpStatusCode.NotModified
break;
case 410: // HttpStatusCode.Gone
break;
case 500: // HttpStatusCode.InternalServerError
break;
// etc
}
}
else
{
//did not contact host. Invalid host name?
}
}
return httpStatusCode;