简体   繁体   English

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

[英]How do I POST a simple POCO using HttpClient?

I have a simple DTO object that looks like the following: 我有一个简单的DTO对象,如下所示:

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

I want to be able to send this object through a POST request to an API endpoint that uses ASP.NET MVC. 我希望能够通过POST请求将此对象发送到使用ASP.NET MVC的API端点。 However I want to make sure that the data is sent using the body of the request, and isn't just appended to the url like in a GET. 但是我想确保数据是使用请求的正文发送的,而不仅仅是像GET中那样附加到URL。

This is simple enough using get requests and can be achieved with the following code. 使用get请求,这很简单,可以使用以下代码来实现。

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

I know that I can serialise the object to a JSON string using a library, but then what do I do with the string? 我知道我可以使用库将对象序列化为JSON字符串,但是该字符串该怎么办?

This is an POST example maybe can useful: 这是一个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();

The easiest way is to the extension method PostAsJsonAsync() 最简单的方法是扩展方法PostAsJsonAsync()

This method will handle any serialization of the object that is necessary. 此方法将处理必需的对象的任何序列化。

From the documentation it can be found 从文档中可以找到

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

Contrived example from the web: 网络上人为的示例:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM