gpt4 book ai didi

c# - 如何使用 System.Net.HttpClient 发布复杂类型?

转载 作者:IT王子 更新时间:2023-10-29 03:35:39 25 4
gpt4 key购买 nike

我有一个自定义的复杂类型,我想使用 Web API 来处理它。

public class Widget
{
public int ID { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}

这是我的 Web API Controller 方法。我想像这样发布这个对象:

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 方法,以及如何构造它。这是一些示例客户端代码。

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 对象?

最佳答案

通用 HttpRequestMessage<T>已被删除。这:

new HttpRequestMessage<Widget>(widget)

不再工作

相反,from this post , ASP.NET 团队已经包含了一些 new calls支持此功能:

HttpClient.PostAsJsonAsync<T>(T value) sends “application/json”
HttpClient.PostAsXmlAsync<T>(T value) sends “application/xml”

因此,新代码 ( from dunston ) 变为:

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() );

关于c# - 如何使用 System.Net.HttpClient 发布复杂类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10304863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com