[更新]
感谢评论中的杰森,我能够找到解决方案。您可以在创建将采用客户端处理程序的其余服务时提供新的 httpClient。在客户端处理程序中覆盖 SendAsync 方法并在此处为每个调用添加所需的请求标头。代码如下。
HttpClientHandler
class AuthenticatedHttpClientHandler : HttpClientHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
request.Headers.Add("platform", Constants.platform);
request.Headers.Add("build", "72");
request.Headers.Add("User-Agent", Constants.platform + " RELEASE");
return await base.SendAsync(request,cancellationToken).ConfigureAwait(false);
}
}
客户端创建
authenticationAPI = RestService.For<IAuthenticationAPI>(new HttpClient(new AuthenticatedHttpClientHandler()) { BaseAddress = new Uri(Constants.RestUrl) });
[问题] 我想在标头中将平台添加到我的改装 API 调用中,但我不想通过方法调用传递它。有没有办法将在运行时创建的标头添加到所有 API 调用?我试过了,但它不起作用,因为它不是一个常数。
[Headers("Content-Type: application/json", Constants.platformHeader)]
单独的常量类
public static string platform = Device.RuntimePlatform == Device.Android? "android" : "iOS";
public const string platformHeader = "platform: " + platform;