2017-09-25 76 views
-2

在我的項目中,我撥打WebApiRefitlink)很多。基本上,我將WebApi定義爲interface。例如:C#和WebApi:如何創建一個通用的基本客戶端

public interface ICustomer 
{ 
    [Get("/v1/customer")] 
    Task<CustomerResponse> GetDetails([Header("ApiKey")] string apikey, 
             [Header("Authorization")] string token, 
             [Header("Referer")] string referer); 
} 

對於每個WebApi,創建一個client那樣:

public async Task<CustomerResponse> GetDetails(string apikey, string token) 
    { 
     CustomerResponse rsl = new CustomerResponse(); 
     rsl.Success = false; 

     var customer = RestService.For<ICustomer>(apiUrl); 
     try 
     { 
      rsl = await customer.GetDetails(apikey, token, apiUrl); 
      rsl.Success = true; 
     } 
     catch (ApiException ax) 
     { 
      rsl.ErrorMessage = ax.Message; 
     } 
     catch (Exception ex) 
     { 
      rsl.ErrorMessage = ex.Message; 
     } 

     return rsl; 
    } 

客戶端之間的唯一區別是接口(在上面的示例代碼ICustomer),返回結構(在示例CustomerResponse來自BaseResponse)以及我必須調用的函數(在示例GetDetails中帶有參數)。

我應該有一個基類,以避免重複的代碼。 在此先感謝。

回答

-1

我喜歡當人們給你一個負面的反饋,沒有任何解釋或解決方案。如果有人有類似的問題,它可以找到我的通用類來解決這個問題。

public class BaseClient<T> where T : IGeneric 
{ 
    public const string apiUrl = "<yoururl>"; 

    public T client; 

    public BaseClient() : base() { 
     client = RestService.For<T>(apiUrl); 
    } 

    public async Task<TResult> ExecFuncAsync<TResult>(Func<TResult> func) 
           where TResult : BaseResponse 
    { 
     TResult rsl = default(TResult); 

     T apikey = RestService.For<T>(apiUrl); 
     try 
     { 
      rsl = func.Invoke(); 
      rsl.Success = true; 
     } 
     catch (ApiException ax) 
     { 
      rsl.ErrorMessage = ax.Message; 
     } 
     catch (Exception ex) 
     { 
      rsl.ErrorMessage = ex.Message; 
     } 

     return rsl; 
    } 

    public async Task<List<TResult>> ExecFuncListAsync<TResult>(Func<List<TResult>> func) 
    { 
     List<TResult> rsl = default(List<TResult>); 

     T apikey = RestService.For<T>(apiUrl); 
     try 
     { 
      rsl = func.Invoke(); 
     } 
     catch (ApiException ax) 
     { 
     } 
     catch (Exception ex) 
     { 
     } 

     return rsl; 
    } 
} 
相關問題