Jac*_*erd 10 c# rest asp.net-mvc json azure-logic-apps
我创建了一个公开 REST 端点的 Azure 逻辑应用程序。
当我通过邮递员调用以下 JSON 正文时,它可以正常工作。
{
"to": "ggtest@yahoo.com",
"subject": "Hello there",
"message": "Hello there!!!!!"
}
Run Code Online (Sandbox Code Playgroud)
我能够看到传入的请求很好地形成
{
"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!!!!!"
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试使用 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);
Run Code Online (Sandbox Code Playgroud)
我能够成功调用我的 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"
}
}
Run Code Online (Sandbox Code Playgroud)
我在这里缺少什么?与邮递员相比,我的 C# 代码有什么不同?
我也刚遇到这个问题。问题似乎是Content-Length标题。在 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);
}
Run Code Online (Sandbox Code Playgroud)
Pac*_*ruz -1
headerTransferEncodingChunked属性应该是false默认的。
不过,试试这个:
var email = new Email
{
to = "gg@live.com.sg",
subject = "from webapp",
message = "hello world"
};
var client = new HttpClient();
var uri = "maskedout";
client.DefaultRequestHeaders.TransferEncodingChunked = false;
var response = await client.PostAsJsonAsync<Email>(uri, email);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4166 次 |
| 最近记录: |