Save Status Code in variable and check

Asked

Viewed 53 times

2

I need to save Statuscode and do a check. I have the following code:

using (HttpResponseMessage response = await httpClient.GetAsync(UrlApi)){}

When I do that: var teste2 = response.StatusCode; the Satuscode returns BadRequest but not saved in variable and I needed to do a check, ex: if(teste2.Equals("BadRequest")){//Faça algo}

2 answers

3


I suggest you convert Statuscode to an integer, and right after, make the desired comparisons.

Something like:

var teste2 = (int)response.StatusCode;

if(teste2 == 400)
{
   Console.WriteLine("Bad Request");
}
else if(teste2 == 200)
{
   Console.WriteLine("OK");
}

1

You can use Enum HttpStatusCode

public class Program
{
    public static void Main()
    {
        var client = new HttpClient();
        client.BaseAddress = new Uri("https://httpbin.org");

        EnviarRequest(client, "uuid");

    }

    public static async void EnviarRequest(HttpClient client, string path)
    {
        using (var response = await client.GetAsync(path))
        {           
            if(response.StatusCode == HttpStatusCode.OK)
                Console.WriteLine("OK");

            if(response.StatusCode == HttpStatusCode.NotFound)
                Console.WriteLine("Not Found");
        }
    }
}
  • Just for the record: I wrote this reply on 01, but I forgot to post.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.