C# – Handling http response codes in GetStringAsync


i'm very new to C#, let alone Windows Phone development 🙂

I'm trying to send a request, get the JSON response, but if there is an error (such as 401), be able to tell the user such. Here is my code:

async Task<string> AccessTheWebAsync()
            //builds the credentials for the web request
            var credentials = new NetworkCredential(globalvars.username, globalvars.password);
            var handler = new HttpClientHandler { Credentials = credentials };

            //calls the web request, stores and returns JSON content
            HttpClient client = new HttpClient(handler);
            Task<string> getStringTask = client.GetStringAsync("https://www.bla.com/content");

            String urlContents = await getStringTask;

            return urlContents;


I know it must be something I'm doing wrong in the way that I send the request and store the response…but i'm just not sure what.

If there is an error, I get a general:

Thank you!

Best Solution

You could use te GetAsync() method instead of the GetStringAsync().

HttpResponseMessage response = await client.GetAsync("https://www.bla.com/content");

     if (response.StatusCode == HttpStatusCode.Unauthorized)
         do something...
String urlContents = await response.Content.ReadAsStringAsync();

This way you can make use of the HttpStatusCode enumerable to check the returned status code.