HttpResponseMessage is IsSuccessStatusCode C#

5k views Asked by At

I have the API in which I am trying to use PutAsync to update some fields. If the Put is successful I have message that will be sent as Response. But if the there are any exception when doing that I will have to send the exception message as response

HttpResponseMessage responseMessage = (await client_Name.PutAsync(c_URL, httpContent));

if (responseMessage.IsSuccessStatusCode)
{
    return Ok(serviceResponse);
}
else
{
    string errormessage = responseMessage.StatusCode.ToString();
}

I am not sure how to handle the HttpResponseMessage exception. I understand responseMessage.StatusCode gives the status but alos not sure how to construct them as response as the return type is Task<IHttpActionResult>

2

There are 2 answers

4
Ilya Chernomordik On BEST ANSWER

It depends on what type of message you would like to send back. Most likely it seems that just 500 is OK. Then you can just return InternalServerError:

return InternalServerError(new Exception(...));

If you want to differentiate among various statuses like 500, 403, etc. you can do that as well. You can use

return Request.CreateErrorResponse()

to send anything back with code, message, etc.

If you just want to server as a kind of proxy and return the code directly, then you can use this:

return new HttpResponseMessage(statusCode)

All in all these are various options to achieve the same result, i.e. to return an http status code with some message back. It's up to you to decide exactly what do you want.

0
Abhishek Maurya On

Try using the following to return :

return Content(HttpStatusCode.BadRequest, "Any object");

Here in object field you can send your error.