-2
在我的項目中,我撥打WebApi
與Refit
(link)很多。基本上,我將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
中帶有參數)。
我應該有一個基類,以避免重複的代碼。 在此先感謝。