c# - PostAsJsonAsync 似乎没有发布正文参数

标签 c# json asp.net-mvc rest azure-logic-apps

我创建了一个公开 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/

相关文章:

asp.net-mvc - NGEN 可以与 Azure 网站一起使用吗?

c# - 如何更新List中item的索引?

c# - 如何在递归中一起执行 bool 表达式列表

javascript - 如何从目录中读取文件并将其作为 JSON 发送给客户端?

java - 如果一个字段的类型未知,Jackson 如何解析 JSON 对象

java - 从 json : wrong characters 读取日文文本

c# - MVC - 生成多个 PDF

c# - 通过直接字符串引用将值传递给实体

c# - 流利的断言 : match each object of a collection

c# - 如何减少 ImageList 的内存使用