Valentin
Valentin

Reputation: 31

IHttpActionResult vs HttpResponseMessage

I want to talk again about differences about IHttpActionResult and HttpResponseMessage. I know that IHttpActionResult is more flexible and good to use with unit testing. But currently I'm working on the project, that was migrated from WebAPI to WebAPi 2, and I want to try replace all usings of HttpResponseMessage with IHttpActionResult. I found in the code next lines:

catch (Exception ex)
{
    return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
}

I want to clarify what is equivalent approach with IHttpActionResult. Is the result in code below will be equivalent to the result in the code above:

catch (Exception ex)
{
    return Content(HttpStatusCode.InternalServerError, ex.Message);
}

Or should I use something else?

Upvotes: 2

Views: 3007

Answers (2)

Manfice
Manfice

Reputation: 199

If you use IHttpActionResult

catch (Exception ex)
{
    return (IHttpActionResult)InternalServerError(exception);
}

Upvotes: 0

Donal
Donal

Reputation: 32723

Ideally, you should wrap it in a ResponseMessage - helps with Content Negotiation:

catch (Exception ex)
{
    return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
}

Upvotes: 3

Related Questions