2017-08-17 1590 views
1

我打電話給我的Web API使用HttpClient,我看到有一個EnsureSuccessStatusCode方法和IsSuccessStatusCode屬性。哪一個是合適的?正確使用EnsureSuccessStatusCode和IsSuccessStatusCode

我看了這篇文章,我有一些其他問題:

Usage of EnsureSuccessStatusCode and handling of HttpRequestException it throws

我遇到的問題是,如果我發送一個GET請求,我通過我希望對象的ID到檢索,基本上有兩種結果:

  1. 我得到的對象返回一個狀態200
  2. 我能得到空回來,因爲沒有比賽,但是這resul ts在404狀態。

如果我打電話EnsureSuccessStatusCode()狀態404將導致引發異常。這是不理想的,因爲當我測試我的代碼時,我一直得到一個404錯誤,這個錯誤起初讓我覺得API URL不正確,但實際上沒有與提供的Id相匹配的對象。在這種情況下,我寧願返回一個空對象,而不是拋出異常。

因此,我嘗試檢查IsSuccessfulStatusCode屬性的值。這似乎是一個更好的選擇,當此屬性爲false時,我可以返回空對象,但是,有許多狀態代碼可能導致此屬性具有錯誤值。 404是其中的一個,但有幾個其他狀態代碼,如400錯誤請求,405方法不允許等我想記錄一個例外,所有不成功的錯誤代碼,除了404和I我想知道是否有更好的方法來做這件事,而不是檢查響應的值ResponseCode,然後拋出一個異常,這個異常被我的catch塊捕獲,這就是日誌發生的地方。

下面是我的GET方法的代碼:

public static Customer GetCustomerByID(int id) 
{ 
    try 
     { 
      using (var client = GetConfiguredClient()) 
      { 
       Customer customer = null; 
       var requestUri = $"Customers/{id}"; 

       using (var response = client.GetAsync(requestUri).Result) 
       { 
        if (response.IsSuccessStatusCode) 
         customer = response.Content.ReadAsAsync<Customer>().Result; 
       } 

       return customer; 
      } 
     } 
     catch (Exception ex) 
     { 
      ex.Data.Add(nameof(id), id); 

      LogException(ex); 

      throw; 
     } 
    } 

這個代碼將只返回一個空Customer如果返回一個非成功的狀態碼沒有東西記錄下來。

處理這種情況的最佳方法是什麼?

回答

3

正因爲如此:

所以不是我試圖檢查IsSuccessfulStatusCode 屬性的值。這似乎是一個更好的選擇,當此屬性爲false時,我可以返回空對象 ,但是,有許多狀態 代碼可能會導致此屬性具有錯誤值。 404是 其中一個,但還有其他幾個狀態代碼,例如400 Bad Request,405 Method Not Allowed等。我想爲 除了404和I'外的所有不成功的錯誤代碼都記錄異常, m想知道 有沒有比檢查響應的值更好的方法來做這件事,然後拋出異常,我的catch塊捕獲 ,這是記錄發生的地方。

我將EnsureSuccessStatusCode方法,並在修改該catch塊象下面這樣:

public static Customer GetCustomerByID(int id) 
{ 
    try 
    { 
     using (var client = GetConfiguredClient()) 
     { 
      var requestUri = $"Customers/{id}"; 
      Customer customer; 

      using (var response = client.GetAsync(requestUri).Result) 
      { 
       try 
       { 
        response.EnsureSuccessStatusCode(); 
        // If we reach here so it means we can get the customer data. 
        customer = response.Content.ReadAsAsync<Customer>().Result; 
       } 
       catch(HttpRequestException) 
       { 
        if(response.StatusCode == HttpStatusCode.NoFound) // 404 
        { 
         customer = null; 
        } 
        else 
        { 
         throw; 
        } 
       } 
      } 

      return customer; 
     } 
    } 
    catch (Exception ex) 
    { 
     ex.Data.Add(nameof(id), id); 

     LogException(ex); 

     throw; 
    } 
}