由于对称性,没有添加需要额外标头的重载:在类型化场景中,您可以为请求指定标头,但无法读取响应中的标头(因为返回类型是类型 T,它不包含标头集合)。
但是,您可以使用可以传递给MobileServiceClient 构造函数的消息处理程序来执行此操作的扩展方法。下面的代码是这种实现的一个例子。它只实现了两个类型化的方法,但如果你想添加其余的方法,实现是微不足道的。
class Program
{
public static MobileServiceClient MobileService = new MobileServiceClient(
"https://YOUR-SERVICE.azure-mobile.net/",
"YOUR-APPLICATION-KEY"
);
static void Main(string[] args)
{
DoWork().Wait();
}
static async Task DoWork()
{
var httpHeaders = new Dictionary<string, string>
{
{ "x-header-1", "value 1" },
{ "x-header-2", "value 2" },
};
var test = await MobileService.InvokeApiWithHeaders<Test>("headers", httpHeaders);
Console.WriteLine("Returned by the service:");
foreach (var k in test.AllHeaderValues.Keys)
{
Console.WriteLine(" {0}: {1}", k, test.AllHeaderValues[k]);
}
}
}
public class Test
{
public Dictionary<string, string> AllHeaderValues { get; set; }
}
public static class TypedInvokeApiWithHeadersExtensions
{
public static Task<T> InvokeApiWithHeaders<T>(this MobileServiceClient client, string apiName, IDictionary<string, string> httpHeaders)
{
var client2 = new MobileServiceClient(client.ApplicationUri, client.ApplicationKey, new AddHeadersHandler(httpHeaders));
return client2.InvokeApiAsync<T>(apiName);
}
public static Task<T> InvokeApiWithHeaders<T>(this MobileServiceClient client, string apiName, HttpMethod method, IDictionary<string, string> httpHeaders, IDictionary<string, string> queryParameters)
{
var client2 = new MobileServiceClient(client.ApplicationUri, client.ApplicationKey, new AddHeadersHandler(httpHeaders));
return client2.InvokeApiAsync<T>(apiName, method, queryParameters);
}
class AddHeadersHandler : DelegatingHandler
{
IDictionary<string, string> headers;
public AddHeadersHandler(IDictionary<string, string> headers)
{
this.headers = headers;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
foreach (var header in headers)
{
request.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
return base.SendAsync(request, cancellationToken);
}
}
}