-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
中带有参数)。
我应该有一个基类,以避免重复的代码。 在此先感谢。