2017-09-25 44 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; 
    } 
} 
相关问题