justme
justme

Reputation: 336

How to convert response of post request to bool in c#?

I have an endpoint in my ASP.NET Core 2.1 Controller

[HttpPost]
public async Task<bool> CheckStatus([FromBody] StatusModel model)
{
...code ommited
return true;
}

And I call this endpoint from other place in code like this:

await client.PostAsync('/CheckStatus', payloayd)

How can I retrive a bool value from this request?

Upvotes: 4

Views: 8585

Answers (1)

Reece Russell
Reece Russell

Reputation: 366

Using Newtonsoft.Json, you can read the response of the request and parse it into a bool.

    using Newtonsoft.Json;

    public async Task<bool> GetBooleanAsync()
    {
        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var data = new { };
            var url = "my site url";

            var payload = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");

            var req = await client.PostAsync(url, payload);
            var response = await req.Content.ReadAsStringAsync();

            return JsonConvert.DeserializeObject<bool>(response);
        }
    }

UPDATE

Looking back on this from a few years on, this can be simplified without the use of Newtonsoft.Json to read the response, by simply parsing the string data to a boolean.

public async Task<bool> GetBooleanAsync()
{
    var data = new { };
    var url = "my site url";

    var payload = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");

    using var client = new HttpClient();
    var response = await client.PostAsync(url, payload);
    var data = await response.Content.ReadAsStringAsync();

    return Boolean.Parse(data);
}

However, if your boolean value is returned in a JSON object, then Newtonsoft.Json could be used to read that value.

Upvotes: 9

Related Questions