使用自定义标头从Azure移动服务中键入结果

时间:2016-01-05 12:45:00

标签: .net rest azure azure-mobile-services

调用Azure移动服务时,我想向自定义REST服务发出请求,并将我的自定义标头值传递到一起,然后返回一个类型化的结果。为什么我没有这个选择?我错过了什么?

查看https://msdn.microsoft.com/en-us/library/azure/microsoft.windowsazure.mobileservices.mobileserviceclient.invokeapiasync.aspx我只能在提出无类型请求时提供自定义标头。

1 个答案:

答案 0 :(得分:2)

由于对称性而未添加额外标头的重载:在类型方案中,您可以为请求指定标头,但无法读取响应中的标头(因为返回类型是类型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);
        }
    }
}