'No response received to multipart/mixed HTTP request

I am trying to use the Dynamics 365 Web API to GET records. The fetch query generated is too long to use a normal GET query so a workaround is to POST the request instead.

I have simplifed the fetch statement here for ease. Ignore the lack of async/await and use of .Result, that can easily be sorted afterwards.

Code:

var clientcred = new ClientCredential(Config.ClientId, Config.ClientSecret);
var authenticationContext = new AuthenticationContext($"{Config.AadInstance}{Config.TenantId}");
var authenticationResult = authenticationContext.AcquireTokenAsync(Config.DynamicsUrl, clientcred).Result;
var token = authenticationResult.AccessToken;

var client = new HttpClient();
client.BaseAddress = new Uri("https://foobar.crm4.dynamics.com");
client.Timeout = new TimeSpan(0, 2, 0);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("OData-Version", "4.0");
client.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
client.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations=\"*\"");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

var req = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, $"/api/data/v9.1/$batch");
var content = "--batch_rob--\n" +
              "Content-Type: application/http\n" +
              "Content-Transfer-Encoding: binary\n" +
              $"GET {Config.BaseUrl}contacts?fetchXml=<fetch count=\"10\" ><entity name=\"contact\" ><attribute name=\"fullname\" /></entity></fetch> HTTP/1.1\n" +
              "OData-Version: 4.0\n" +
              "OData-MaxVersion: 4.0\n" +
              "--batch_rob--";
using (var content2 = new MultipartContent())
{
    content2.Add(new StringContent(content));
    content2.Headers.Remove("Content-Type");
    content2.Headers.TryAddWithoutValidation("Content-Type", "multipart/mixed;boundary=batch_rob");

    var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, $"/api/data/v9.1/$batch")
    {
        Content = content2
    };

    var response = client.SendAsync(request).Result;
    var outcome2 = response.Content.ReadAsStringAsync().Result;
}

This all compiles and appears to run fine. The response however does not contain the JSON I expect (the result of the GET query) but rather is just:

--batchresponse_20851dc6-4ff6-4914-a749-66f451985f67--

Any idea what I have missed?

This is based on the example demonstrated here: https://dreamingincrm.com/2017/01/15/executing-large-fetchxml-with-webapi/



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source