无法同时发布元数据和多部分内容。收到400错误请求

时间:2019-06-06 17:31:27

标签: c# .net uwp

我正在尝试从我的UWP应用上传文件并在查询参数(以下代码)中添加一些JSON数据。但是,我收到一个400错误的请求。不知道我在这里想念的是什么。但是,我可以从邮递员执行相同操作,并获得200 OK。

有人可以帮忙吗?

        string apiUrl = BuildUrl(url, apiContext);

        // req params which has the json string as key value pair and few other request parameters
        Uri uri = BuildUriWithQueryParams(apiUrl, reqParams);

        HttpRequestMessage reqMsg = new HttpRequestMessage(HttpMethod.Post, uri);

        // File upload
        if (files != null && files.Count > 0)
        {
            HttpMultipartFormDataContent formDataContent = new HttpMultipartFormDataContent();
            foreach (StorageFile storageFile in files)
            {
                var inputStream = await storageFile.OpenAsync(FileAccessMode.Read);
                HttpStreamContent httpStreamContent = new HttpStreamContent(inputStream);
                formDataContent.Add(httpStreamContent, "doc", storageFile.Name);
            }
            reqMsg.Content = formDataContent;
        }
        var response = await HttpClient.SendRequestAsync(reqMsg);//.AsTask(cts.Token);

1 个答案:

答案 0 :(得分:1)

从查询参数中删除JSON req参数并添加到HttpStringContent为我解决了这个问题。下面提到了所需的更改。

 string apiUrl = BuildUrl(url, apiContext);

        // req params which has the json string as key value pair and few other request parameters
//    Uri uri = BuildUriWithQueryParams(apiUrl, reqParams);
      UriBuilder uriBuilder = new UriBuilder(apiUrl);

        HttpRequestMessage reqMsg = new HttpRequestMessage(HttpMethod.Post, uriBuilder .Uri);

        HttpMultipartFormDataContent formDataContent = new HttpMultipartFormDataContent();

        // File upload
        if (files != null && files.Count > 0)
        {
            foreach (StorageFile storageFile in files)
            {
                var inputStream = await storageFile.OpenAsync(FileAccessMode.Read);
                HttpStreamContent httpStreamContent = new HttpStreamContent(inputStream);
                formDataContent.Add(httpStreamContent, "doc", storageFile.Name);
            }
        }
            foreach (KeyValuePair<string, string> keyValuePair in reqParams)
                formDataContent.Add(new HttpStringContent(keyValuePair.Value), keyValuePair.Key);
            reqMsg.Content = formDataContent;

        var response = await HttpClient.SendRequestAsync(reqMsg);//.AsTask(cts.Token);