如何使用 System.Net.HttpClient 发布复杂类型? [英] How to use System.Net.HttpClient to post a complex type?
问题描述
我有一个自定义的复杂类型,我想使用 Web API 使用它.
I have a custom complex type that I want to work with using Web API.
public class Widget
{
public int ID { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
这是我的 Web API 控制器方法.我想像这样发布这个对象:
And here is my web API controller method. I want to post this object like so:
public class TestController : ApiController
{
// POST /api/test
public HttpResponseMessage<Widget> Post(Widget widget)
{
widget.ID = 1; // hardcoded for now. TODO: Save to db and return newly created ID
var response = new HttpResponseMessage<Widget>(widget, HttpStatusCode.Created);
response.Headers.Location = new Uri(Request.RequestUri, "/api/test/" + widget.ID.ToString());
return response;
}
}
现在我想使用 System.Net.HttpClient
来调用该方法.但是,我不确定将什么类型的对象传递到 PostAsync
方法,以及如何构造它.这是一些示例客户端代码.
And now I'd like to use System.Net.HttpClient
to make the call to the method. However, I'm unsure of what type of object to pass into the PostAsync
method, and how to construct it. Here is some sample client code.
var client = new HttpClient();
HttpContent content = new StringContent("???"); // how do I construct the Widget to post?
client.PostAsync("http://localhost:44268/api/test", content).ContinueWith(
(postTask) =>
{
postTask.Result.EnsureSuccessStatusCode();
});
如何以 Web API 能够理解的方式创建 HttpContent
对象?
How do I create the HttpContent
object in a way that web API will understand it?
推荐答案
通用 HttpRequestMessage
已删除.这:
new HttpRequestMessage<Widget>(widget)
将不再起作用.
相反,来自这篇博文,ASP.NET 团队包含了一些新调用以支持此功能:
Instead, from this post, the ASP.NET team has included some new calls to support this functionality:
HttpClient.PostAsJsonAsync<T>(T value) sends "application/json"
HttpClient.PostAsXmlAsync<T>(T value) sends "application/xml"
因此,新代码(来自 Dunston)变为:
So, the new code (from dunston) becomes:
Widget widget = new Widget()
widget.Name = "test"
widget.Price = 1;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:44268");
client.PostAsJsonAsync("api/test", widget)
.ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode() );
这篇关于如何使用 System.Net.HttpClient 发布复杂类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!