8

I've created an API in .NET Core 2 using C#. It returns an ActionResult with a status code and string message. In another application, I call the API using Flurl. I can get the status code number, but I can't find a way to get the message. How do I get the message or what do I need to change in the API to put the message someway Flurl can get it?

Here's the code for the API. The "message" in this example is "Sorry!".

[HttpPost("{orderID}/SendEmail")]
[Produces("application/json", Type = typeof(string))]
public ActionResult Post(int orderID)
{
    return StatusCode(500, "Sorry!");
}

Here's the code in another app calling the API. I can get the status code number (500) using (int)getRespParams.StatusCode and the status code text (InternalError) using getRespParams.StatusCode, but how do I get the "Sorry!" message?

var getRespParams = await $"http://localhost:1234/api/Orders/{orderID}/SendEmail".PostUrlEncodedAsync();
int statusCodeNumber = (int)getRespParams.StatusCode;
haindl
  • 3,111
  • 2
  • 25
  • 31
boilers222
  • 1,901
  • 7
  • 33
  • 71

1 Answers1

18

PostUrlEncodedAsync returns an HttpResponseMessage object. To get the body as a string, just do this:

var message = await getRespParams.Content.ReadAsStringAsync();

One thing to note is that Flurl throws an exception on non-2XX responses by default. (This is configurable). Often you only care about the status code if the call is unsuccessful, so a typical pattern is to use a try/catch block:

try {
    var obj = await url
        .PostAsync(...)
        .ReceiveJson<MyResponseType>();
}
catch (FlurlHttpException ex) {
    var status = ex.Call.HttpStatus;
    var message = await ex.GetResponseStringAsync();
}

One advantage here is you can use Flurl's ReceiveJson to get the response body directly in successful cases, and get the error body (which is a different shape) separately in the catch block. That way you're not dealing with deserializing a "raw" HttpResponseMessage at all.

haindl
  • 3,111
  • 2
  • 25
  • 31
Todd Menier
  • 37,557
  • 17
  • 150
  • 173