Search code examples
c#asp.netasp.net-mvcasp.net-web-apihttpresponsemessage

HttpResponseMessage is IsSuccessStatusCode C#


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>


Solution

  • 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.