在HttpClient MultipartFormDataContent中的意外时间调用了一个方法

时间:2015-04-17 06:34:48

标签: c# winrt-httpclient

我必须将多部分数据发布到服务器,但我收到的错误

enter image description here

我正在使用以下代码

  public async static Task<string> HttpImagePostMethod(byte[] wInputData, string Uri, string path)
    {
        string result = string.Empty;
        try
        {
            #region For Https (Secure) Api having SSL
            var filter = new HttpBaseProtocolFilter();
            filter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Untrusted);
            var client = new System.Net.Http.HttpClient(new WinRtHttpClientHandler(filter));
            #endregion

            MultipartFormDataContent requestContent = new MultipartFormDataContent();

            //   StreamContent content = new StreamContent(wInputData);
            var content = new ByteArrayContent(wInputData);
            content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");

            requestContent.Add(content, "file", path);               
            requestContent.Headers.Add("X-API-Key", UrlFactory.X_API_Key_Value);
            requestContent.Add(new StringContent("144"), "type");

            HttpResponseMessage aResp = await client.PostAsync(UrlFactory.BaseUrl + Uri, requestContent);

            if (aResp.IsSuccessStatusCode)
            {
                result = await aResp.Content.ReadAsStringAsync();
            }
            else
            {
                result = await aResp.Content.ReadAsStringAsync();
            }
        }
        catch (Exception ex)
        {
            result = string.Empty;
        }
        return result;
    }

我在这一行收到错误

  

HttpResponseMessage aResp = await client.PostAsync(UrlFactory.BaseUrl + Uri,requestContent);

由于这条线

  

requestContent.Headers.Add(“X-API-Key”,UrlFactory.X_API_Key_Value);

2 个答案:

答案 0 :(得分:1)

我自己回答这个问题可能对我的其他朋友有帮助......

  HttpRequestMessage httpRequest = new HttpRequestMessage();
            httpRequest.Method = HttpMethod.Post;
            httpRequest.RequestUri = new System.Uri(UrlFactory.BaseUrl + Uri);
            httpRequest.Content = requestContent;

            httpRequest.Headers.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
            httpRequest.Headers.TryAddWithoutValidation("X-API-Key", UrlFactory.X_API_Key_Value);

客户端(HttpClient)不应包含任何标头,我们在HttpRequestMessage中声明标头

答案 1 :(得分:0)

正如错误消息所示,您尝试在内容上设置标题,但它并不属于那里;您的API令牌是请求本身的属性,而不是其内容的属性 请尝试将该标题添加到client.DefaultRequestHeaders