Conteúdo do Curso
Introduction to .NET with C#
2. Asynchronous Programming and Introduction to Web Services
3. Introduction to Databases with .NET
Introduction to .NET with C#
Task - Exception Handling for API Response
The task is to work on the code from the previous task, and add error checking, exactly the way we did in the video.
You don't need to add error checking for int.Parse
methods.
Note
This task does not have test cases. You can verify your solution by comparing it to the given solution code.
2. Check if the request was successful by using the
IsSuccessStatusCode
attribute of the response class.
class NumbersFact
{
static async Task Main()
{
Console.WriteLine(">> This program gives you a random fact about any day of the year. ");
Console.Write("Enter the number of month (1-12): ");
int month = int.Parse(Console.ReadLine());
Console.Write("Enter the number of day: ");
int day = int.Parse(Console.ReadLine());
// Write code below this line
try
{
string url = $"http://numbersapi.com/{month}/{day}/date";
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
string responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine("Fact: " + responseContent);
}
else
{
Console.WriteLine($"API request failed: {response.StatusCode}");
}
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
// Write code above this line
}
}
Tudo estava claro?
Conteúdo do Curso
Introduction to .NET with C#
2. Asynchronous Programming and Introduction to Web Services
3. Introduction to Databases with .NET
Introduction to .NET with C#
Task - Exception Handling for API Response
The task is to work on the code from the previous task, and add error checking, exactly the way we did in the video.
You don't need to add error checking for int.Parse
methods.
Note
This task does not have test cases. You can verify your solution by comparing it to the given solution code.
2. Check if the request was successful by using the
IsSuccessStatusCode
attribute of the response class.
class NumbersFact
{
static async Task Main()
{
Console.WriteLine(">> This program gives you a random fact about any day of the year. ");
Console.Write("Enter the number of month (1-12): ");
int month = int.Parse(Console.ReadLine());
Console.Write("Enter the number of day: ");
int day = int.Parse(Console.ReadLine());
// Write code below this line
try
{
string url = $"http://numbersapi.com/{month}/{day}/date";
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
string responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine("Fact: " + responseContent);
}
else
{
Console.WriteLine($"API request failed: {response.StatusCode}");
}
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
// Write code above this line
}
}
Tudo estava claro?