我创建了一个公开 REST 端点的 Azure 逻辑应用程序。
当我通过 postman 调用时,以下 JSON 主体工作正常。
{
"to": "ggtest@yahoo.com",
"subject": "Hello there",
"message": "Hello there!!!!!"
}
我能够很好地看到传入的请求
{
"headers": {
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Accept": "*/*",
"Accept-Encoding": "gzip,deflate",
"Host": "maskedout.northcentralus.logic.azure.com:443",
"User-Agent": "PostmanRuntime/6.4.1",
"Content-Length": "99",
"Content-Type": "application/json"
},
"body": {
"to": "ggtest@yahoo.com",
"subject": "Hello there",
"message": "Hello there!!!!!"
}
}
但是,当我尝试使用带有此代码的 C# PostAsJsonAsync 进行相同的调用时:
var email = new Email
{
to = "gg@live.com.sg",
subject = "from webapp",
message = "hello world"
};
var client = new HttpClient();
var uri = "maskedout";
var response = await client.PostAsJsonAsync<Email>(uri, email);
我能够成功调用我的 REST 端点,但它不包含正文
这是我看到的传入请求:
{
"headers": {
"Connection": "Keep-Alive",
"Transfer-Encoding": "chunked",
"Host": "maskedout.northcentralus.logic.azure.com",
"x-ms-request-root-id": "9e5513c2-43961642a3688718",
"x-ms-request-id": "|9e5513c2-43961642a3688718.1.",
"Request-Id": "|9e5513c2-43961642a3688718.1.1.",
"Content-Type": "application/json; charset=utf-8",
"Content-Length": "0"
}
}
我在这里错过了什么?与 postman 相比,我的 C# 代码有何不同?
最佳答案
我也遇到了这个问题。问题似乎是 Content-Length
header 。在 Postman 中,它是内容的长度,但使用 HttpClient 时,长度为 0,所以我猜测端点忽略了正文,因为它被告知它是空的。
我创建了自己的扩展来解决这个问题:
public static async Task<HttpResponseMessage> PostJsonAsync<T>(
this HttpClient client,
string requestUri,
T value)
{
var data = JsonConvert.SerializeObject(value);
var content = new StringContent(data,
Encoding.UTF8,
MimeTypes.Json);
Debug.WriteLine(client.BaseAddress + requestUri);
return await client.PostAsync(requestUri,
content)
.WithRequestTimeout()
.ConfigureAwait(false);
}
关于c# - PostAsJsonAsync 似乎没有发布正文参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47816551/