数据未显示在HttpClient请求中

问题描述 投票:0回答:1

我有一个控制台应用程序,它从一个对象中获取数据,然后将其序列化为json ...我做了很多调整,现在我在各处设置了Authorization和content类型,因为我认为这可能是问题所在。这可能是问题的一部分,但现在我发现不再传递我的数据对象。

我将不胜感激。

//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;
}
json request httpclient bearer-token
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.