【问题标题】:How do I POST a simple POCO using HttpClient?如何使用 HttpClient 发布一个简单的 POCO?
【发布时间】:2019-04-30 13:27:19
【问题描述】:

我有一个简单的 DTO 对象,如下所示:

public class InstructionComponents
    {
        public int ApplicationNumber { get; set; }
        public string FurtherComments { get; set; }
    }

我希望能够通过 POST 请求将此对象发送到使用 ASP.NET MVC 的 API 端点。但是我想确保数据是使用请求的主体发送的,而不是像 GET 那样只是附加到 url。

这使用get请求很简单,可以通过以下代码实现。

            var url = //endpoint url   
            using(var httpClient = new HttpClient())
            {
                var response = httpClient.GetStringAsync(url).Result;
                return result;
            }

我知道我可以使用库将对象序列化为 JSON 字符串,但是我该如何处理该字符串?

【问题讨论】:

标签: c# asp.net asp.net-mvc


【解决方案1】:

这是一个 POST 示例,可能有用:

 var values = new Dictionary<string, string>
    {
       { "thing1", "hello" },
       { "thing2", "world" }
    };

    var content = new FormUrlEncodedContent(values);

    var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);

    var responseString = await response.Content.ReadAsStringAsync();

【讨论】:

【解决方案2】:

最简单的方法是扩展方法PostAsJsonAsync()

此方法将处理任何必要的对象序列化。

从文档中可以找到

命名空间:System.Net.Http 程序集:System.Net.Http.Formatting(在 System.Net.Http.Formatting.dll 中)

来自网络的人为示例:

static async Task<Uri> CreateProductAsync(Product product)
{
    HttpResponseMessage response = await client.PostAsJsonAsync(
        "api/products", product);
    response.EnsureSuccessStatusCode();

    // return URI of the created resource.
    return response.Headers.Location;
}

【讨论】:

    猜你喜欢
    • 2011-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-22
    • 1970-01-01
    相关资源
    最近更新 更多