c# - 将 StringContent Json 转换为 byte[]
问题描述
// 需要使用这个人在 byte[] 中转换成 Json 来完成 api,我尝试了一些我在这里找到的不同方法,但我无法让它工作 heelp
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
需要 a char[]
or string
。但是您试图传递一个StringContent
类型化的对象并且编译器没有可用的转换。但是:你甚至不需要那个!
由于StringContent
"is-a" ByteArrayContent
( .. "is-a" HttpContent
,这是预期的PostAsync
),只需将其传递给PostAsync
:
response = await client.PostAsync(uri, data);
当然,和往常一样:不要在每次调用中创建一个新的 HttpClient!
HttpClient 旨在被实例化一次并在应用程序的整个生命周期中重复使用。为每个请求实例化一个 HttpClient 类将耗尽重负载下可用的套接字数量。这将导致 SocketException 错误。- 来源
推荐阅读
- amazon-web-services - Cloudformation CustomResource“响应不是有效的 JSON”
- javascript - 如何删除……在一个变量中
- javascript - 在three.js中从一个坐标空间转换为另一个
- logging - Datadog:类别处理器-将日志定义为错误-无法将日志解析为错误
- reactjs - 如何在 React 中创建子域?
- pandas - 在数据框中取一定的值
- html - 如何有条件地在 Nuxt/Vue 中设置链接样式
- c# - 环境变量如何知道我正在运行的环境以及如何在 C# 中设置它们?
- vue.js - 只需在prosemiror中替换节点的内容
- javascript - 在 Node.js 中解压缩和处理文件