如何使用System.Net.HttpClient发布的复杂类型? [英] How to use System.Net.HttpClient to post a complex type?

查看:217
本文介绍了如何使用System.Net.HttpClient发布的复杂类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义的复杂类型,我想使用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方法,以及如何构建它。下面是一些简单的客户端code。

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

如何创建在某种程度上HttpContent对象的Web API会理解呢?

How do I create the HttpContent object in a way that web API will understand it?

推荐答案

通用的Htt prequestMessage&LT; T&GT; 删除 。这样的:

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"

所以,新的code(从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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆