Данные не отображаются в запросе HttpClient - PullRequest
0 голосов
/ 14 апреля 2020

У меня есть консольное приложение, которое берет данные из объекта, а затем сериализует их в json ... Я сделал много настроек, и теперь у меня везде устанавливаются тип авторизации и содержимого, потому что я подумал, что была проблема. Это может быть частью проблемы, но теперь я обнаружил, что мой объект данных больше не передается.

Буду признателен за любую помощь.

//Call is kicked off here
public static async Task TransmitToService(IList selectedItems, CancellationToken cancellationToken)
{
    await TransmitRecords.ProcessItems(selectedItems, cancellationToken);
}

private const string BaseURL = "https://base.com/"; // read in from config table
private const string itemUrl = "url/item/null/"; // read in from config table
private static readonly UTF8Encoding _utf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);

public static async Task ProcessItems(object content, CancellationToken cancellationToken)
{
    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Accept.Clear();
        client.BaseAddress = new Uri(BaseURL);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "code");

        using (var request = new HttpRequestMessage(HttpMethod.Post, itemUrl))

        using (var httpContent = CreateHttpContent(content))
        {
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "code");

            request.Content = httpContent;

            using (var response = await client
                .SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken)
                .ConfigureAwait(false))
            {
                response.EnsureSuccessStatusCode();
            }
        }
    }
}
public static void SerializeJsonIntoStream(object value, Stream stream)
{
    using (var sw = new StreamWriter(stream, _utf8, 1024, true))
    using (var jtw = new JsonTextWriter(sw) { Formatting = Formatting.None })
    {
        var js = new JsonSerializer();
        js.Serialize(jtw, value);
        jtw.Flush();
    }
}
private static HttpContent CreateHttpContent(object content)
{
    HttpContent httpContent = null;

    if (content != null)
    {
        var ms = new MemoryStream();
        SerializeJsonIntoStream(content, ms);
        ms.Seek(0, SeekOrigin.Begin);
        httpContent = new StreamContent(ms);
        httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        httpContent.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "code")
    }

    return httpContent;
}
...