【问题标题】:C# and WebApi: how to create a common base clientC# 和 WebApi:如何创建通用基础客户端
【发布时间】:2018-03-06 07:41:09
【问题描述】:

在我的项目中,我用Refit (link) 调用了很多WebApi。基本上,我将WebApi 定义为interface。例如:

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 带参数)。

我应该有一个基类以避免重复代码。 提前致谢。

【问题讨论】:

    标签: c# asp.net-web-api base-class


    【解决方案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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-01
      • 2014-05-24
      • 2020-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多