ฉันไม่ชอบ SureSuccessStatusCode เพราะมันไม่ส่งคืนอะไรที่มีความหมาย นั่นคือเหตุผลที่ฉันสร้างส่วนขยายของตัวเอง:
public static class HttpResponseMessageExtensions
{
    public static async Task EnsureSuccessStatusCodeAsync(this HttpResponseMessage response)
    {
        if (response.IsSuccessStatusCode)
        {
            return;
        }
        var content = await response.Content.ReadAsStringAsync();
        if (response.Content != null)
            response.Content.Dispose();
        throw new SimpleHttpResponseException(response.StatusCode, content);
    }
}
public class SimpleHttpResponseException : Exception
{
    public HttpStatusCode StatusCode { get; private set; }
    public SimpleHttpResponseException(HttpStatusCode statusCode, string content) : base(content)
    {
        StatusCode = statusCode;
    }
}
ซอร์สโค้ดสำหรับรหัส SureSuccessStatusCode ของ Microsoft สามารถพบได้ที่นี่
เวอร์ชันซิงโครนัสตามลิงค์ SO :
public static void EnsureSuccessStatusCode(this HttpResponseMessage response)
{
    if (response.IsSuccessStatusCode)
    {
        return;
    }
    var content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
    if (response.Content != null)
        response.Content.Dispose();
    throw new SimpleHttpResponseException(response.StatusCode, content);
}
สิ่งที่ฉันไม่ชอบเกี่ยวกับ IsSuccessStatusCode ก็คือมันไม่สามารถใช้ซ้ำได้ "อย่างดี" ตัวอย่างเช่นคุณสามารถใช้ไลบรารีเช่นpollyเพื่อทำคำขอซ้ำในกรณีที่มีปัญหาเครือข่าย ในกรณีนี้คุณต้องใช้รหัสของคุณเพื่อเพิ่มข้อยกเว้นเพื่อให้พอลลี่หรือไลบรารีอื่น ๆ สามารถจัดการได้ ...