Last post Aug 03, 2016 05:50 AM by Yohann Lu
Aug 02, 2016 03:44 PM|vs2010junkie|LINK
I am writing some code around using the HttpClient and I found this article: http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client
However, this example is very basic and does not cover any information about handling different return codes from Web API methods specifically such as handling NotFound, NoContent, Created, BadRequest vs. InternalServerError codes.
I would like my HttpClient to be able to distinguish between these various Status Codes rather than simply determining whether or not a Success or Failure occurred.
Is there any better documentation or code samples that addresses this specific requirement?
Aug 02, 2016 05:07 PM|PatriceSc|LINK
Have you seen https://msdn.microsoft.com/en-us/library/system.net.http.httpresponsemessage.statuscode(v=vs.118).aspx ? Your intent is to
add this info for diagnostics purpose or do you want rather to handle at least some of those status as something that could happen in normal operation?
Aug 02, 2016 11:36 PM|vs2010junkie|LINK
I am using an HttpClient through my Client Application so I want to present different messages to the user based on the results returned from the Web API layer. Therefore, I should be able to determine if I received an Accepted Status Code vs. a NotFound
Result vs a Created or CreatedAtRoute result.
Please advise as to how to achieve this.
Aug 03, 2016 05:50 AM|Yohann Lu|LINK
would like my HttpClient to be able to distinguish between these various Status Codes rather than simply determining whether or not a Success or Failure occurred.
You can try the following code.
HttpClient client = new HttpClient();
Uri baseAddress = new Uri("baseUrl");
client.BaseAddress = baseAddress;
HttpResponseMessage response = client.PostAsJsonAsync("api/Values", "Test").Result;
//get states code
int responsestate = (int)response.StatusCode;
if (response.StatusCode == HttpStatusCode.NotFound)
else if (response.StatusCode == HttpStatusCode.OK)
string s = response.Content.ToString();
HttpStatusCode (the type of response.StatusCode):