Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the message from an API using Flurl?

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;
like image 621
boilers222 Avatar asked May 31 '18 18:05

boilers222


People also ask

What does Flurl mean?

So, What is Flurl? Flurl stands for the Fluent URL. Quoting Flurl's home page: Flurl is a modern, fluent, asynchronous, testable, portable, buzzword-laden URL builder and HTTP client library for . NET. It's simple as that.

What is FlurlClient?

FlurlClient is a lightweight wrapper around HttpClient and is tightly bound to its lifetime. It implements IDisposable , and when disposed will also dispose HttpClient . FlurlClient includes a BaseUrl property, as well as Headers , Settings , and many of the fluent methods you may already be familiar with.


1 Answers

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.

like image 165
Todd Menier Avatar answered Sep 22 '22 07:09

Todd Menier