I am throwing a WebException if something is wrong
Oh no, don't. If something gets wrong in your Web API set the corresponding response status code.
For example:
public HttpResponseMessage Get(int id)
{
var model = this.repository.Get(id);
if (model == null)
{
return Request.CreateErrorResponse(
HttpStatusCode.NotFound,
string.Format("Sorry but we couldn't find a resource with id={0}", id)
);
}
return Request.CreateResponse(HttpStatusCode.OK, model);
}
and then on the client:
using (var client = new WebClient())
{
try
{
string result = client.DownloadString("http://example.com/api/someresources/123");
}
catch (WebException ex)
{
// get the status code:
var response = (HttpWebResponse)ex.Response;
var statusCode = response.StatusCode;
// you could also read the response stream:
using (var reader = new StreamReader(response.GetResponseStream()))
{
// now you could read the body
string body = reader.ReadToEnd();
}
}
}