c# - 将 StringContent JSON 转换为 byte[]

标签 c# rest dotnet-httpclient

需要使用这个byte[]里面转换成JSON来完成API。我尝试了在这里找到的一些不同的方法,但我无法使其发挥作用。帮助。

    static async void MakeRequest()
    {
        var client = new HttpClient();
        var queryString = HttpUtility.ParseQueryString(string.Empty);

            var person = new Person();
            person.id = "1234";
            person.Name = "John Doe";
            person.Email = "  ";
            person.individualIdentificationCode = "0000";
            person.order = "1";
            person.action = "DIGITAL-SIGNATURE";
            person.signurl = "https://sandbox.portaldeassinaturas.com.br/Assinatura/AssinarEletronicoFrame/152124?chave=";

            var json = JsonConvert.SerializeObject(person);
            var data = new StringContent(json, Encoding.UTF8, "application/json");
            
            // Request headers
            client.DefaultRequestHeaders.Add("Token", "{}");

            var uri = "https://api-sbx.portaldeassinaturas.com.br/api/v2/document/create?" + queryString;

            HttpResponseMessage response;

            // Request body
            byte[] byteData = Encoding.UTF8.GetBytes(data);

            using (var content = new ByteArrayContent(byteData))
            {
                content.Headers.ContentType = new 
 MediaTypeHeaderValue("application/Json");
                response = await client.PostAsync(uri, content);
            }

        }
    }
}

最佳答案

您看到的错误是因为 GetBytes 需要 char[]string 。但你正试图通过 StringContent类型化对象,并且编译器没有可用的转换。 但是:你甚至不需要那个!

由于 StringContent "is-a"ByteArrayContent ( .. "is-a"HttpContent,这是 PostAsync 所期望的),只需将其传递给 PostAsync:

response = await client.PostAsync(uri, data);

并且当然,一如既往:不要在每次调用中创建新的 HttpClient!

HttpClient is intended to be instantiated once and re-used throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors. - Source

关于c# - 将 StringContent JSON 转换为 byte[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65022092/

相关文章:

c# - C# 中的 Interbase 事件支持

c# - 确定类是否是具有多个泛型参数的类型的子类

c# - 来自 C# 类的 JavaScript 警报

java - 将 Rest 服务添加到 Struts 应用程序

c# - Web Api 2 Controller 和处理程序之间有五秒的延迟

c# - Xamarin 表单 HttpClient 卡住

c# - 递归到动态函数

java - Spring Security、无状态 REST 服务和 CSRF

java - 在 Rest 服务中返回动态 Json

c# - 如何为 HttpClient 调用配置网络跟踪 Dotnet 核心?