C# .NET 6 呼叫 API 示範

最簡單呼叫 API 取得資料

    
HttpClient httpClient = new();
HttpResponseMessage httpResponseMessage = httpClient.GetAsync("https://cdn.jsdelivr.net/gh/ruyut/TaiwanCalendar/data/2023.json").Result;

int statusCode = (int) httpResponseMessage.StatusCode;
Console.WriteLine($"Http 狀態碼: {statusCode}");

string content = httpResponseMessage.Content.ReadAsStringAsync().Result;
Console.WriteLine($"Http 回應內容: {content}");
    

若要直接將 Json 反序列化變為物件可以直接這樣:
    
HttpClient httpClient = new();
List<TaiwanCalenderDto>? result = httpClient.GetFromJsonAsync<List<TaiwanCalenderDto>>("https://cdn.jsdelivr.net/gh/ruyut/TaiwanCalendar/data/2023.json").Result;

result?.ForEach(Console.WriteLine);

/// <summary>
/// TaiwanCalendar Json Data
/// </summary>
public class TaiwanCalenderDto
{
    [JsonPropertyName("date")] public string Date { get; set; }
    [JsonPropertyName("week")] public string Week { get; set; }
    [JsonPropertyName("isHoliday")] public bool IsHoliday { get; set; }
    [JsonPropertyName("description")] public string Description { get; set; }

    public override string ToString()
    {
        return $"日期: {Date}, 星期: {Week}, 是否為假日: {IsHoliday}, 假日名稱: {Description}";
    }
}
    

不過要注意,上面為了程式碼簡單所以都直接等待到得到 API 回應後做處理,這樣做可能造成介面卡死或是浪費等待回應的時間,並且也沒有作錯誤處理,如果 API 呼叫失敗會直接拋出例外,造成應用程式終止。

留言