如何使用HttpClient发布简单的POCO?

问题描述 投票:0回答:2

我有一个简单的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
2个回答
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();

0
投票

最简单的方法是扩展方法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;
}
© www.soinside.com 2019 - 2024. All rights reserved.