【问题标题】:How to add own header to Azure Mobile Services call?如何将自己的标头添加到 Azure 移动服务调用?
【发布时间】:2015-03-25 14:15:32
【问题描述】:

我有 Azure 移动服务 API,我想从 Windows Phone 应用程序调用它。

所以我使用类似的东西:

public static async Task<bool> InvokeGetUsers()
        {
            Dictionary<string, string> headers = new Dictionary<string, string>();
            headers.Add("X-USER-TOKEN", App.userInfo.token);
            headers.Add("X-ZUMO-APPLICATION", "nxdQEvWOERLaHocwMz");

            Dictionary<string, string> arguments = new Dictionary<string, string>();
            arguments.Add("uuid", "123456");

            if (App.mobileServiceClient != null)
            {
                App.userFriends = await App.mobileServiceClient.InvokeApiAsync<List<GetUsers>>("get_users", System.Net.Http.HttpMethod.Post, arguments);
                return true;
            }
            return false;
        }

我不能将标头信息传递给我的调用,该怎么做?

【问题讨论】:

    标签: c# azure windows-phone-8 azure-mobile-services


    【解决方案1】:

    您可以使用 InvokeApiAsync 方法的重载版本:

    public Task<HttpResponseMessage> InvokeApiAsync(
        string apiName,
        HttpContent content,
        HttpMethod method,
        IDictionary<string, string> requestHeaders,
        IDictionary<string, string> parameters
    )
    

    更多信息在这里:https://msdn.microsoft.com/en-us/library/dn268343.aspx

    【讨论】:

    • 我应该使用什么样的HttpContent - 因为上面的版本不需要指定它。
    • 因为它是一个获取请求,所以您不应该发送任何内容,即。 e 将其设置为 null。
    【解决方案2】:

    理想情况下,您希望通过 MobileServiceClient 向 API 的所有调用添加标头。为此,您需要实现 Http Message Handler 并将其传递给 MobileServiceClient 的构造函数,例如

    App.mobileServiceClient = new MobileServiceClient(apiURI, new MyHandler());
    

    这里是Handler的实现:

    public class MyHandler : DelegatingHandler
    {
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            request.Headers.Add("x-api-key", "1234567");
            var response = await base.SendAsync(request, cancellationToken);
            return response;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多