如何将对象传递给HttpClient.PostAsync并序列化为JSON主体? [英] How do I pass an object to HttpClient.PostAsync and serialize as a JSON body?

查看:734
本文介绍了如何将对象传递给HttpClient.PostAsync并序列化为JSON主体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用System.Net.Http,我在网上找到了几个示例.我设法创建了此代码以发出POST请求:

I'm using System.Net.Http, I found several examples on the web. I managed to create this code for make a POST request:

public static string POST(string resource, string token)
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(baseUri);
        client.DefaultRequestHeaders.Add("token", token);

        var content = new FormUrlEncodedContent(new[]
        {
             new KeyValuePair<string, string>("", "")
        });

        var result = client.PostAsync("", content).Result;
        string resultContent = result.Content.ReadAsStringAsync().Result;
        return resultContent;
    }
 }

一切正常.但是,假设我想将第三个参数传递给POST方法,即称为data的参数.数据参数是这样的对象:

all working fine. But suppose that I want pass a third param to the POST method, a param called data. The data param is an object like this:

object data = new
{
    name = "Foo",
    category = "article"
};

如何在不创建KeyValuePair的情况下执行此操作?我的PHP RestAPI等待json输入,因此FormUrlEncodedContent应该正确发送raw json.但是如何使用Microsoft.Net.Http做到这一点?谢谢.

how can I do that without create the KeyValuePair? My php RestAPI wait a json input, so the FormUrlEncodedContent should send the raw json correctly. But how can I do this with Microsoft.Net.Http? Thanks.

推荐答案

您的问题的直接答案是:否.

The straight up answer to your question is: No. The signature for the PostAsync method is as follows:

公共任务PostAsync(Uri requestUri,HttpContent内容)

public Task PostAsync(Uri requestUri, HttpContent content)

因此,尽管您可以将object传递给PostAsync,但它必须是HttpContent类型,并且您的匿名类型不符合该条件.

So, while you can pass an object to PostAsync it must be of type HttpContent and your anonymous type does not meet that criteria.

但是,有一些方法可以完成您想要完成的任务.首先,您需要将匿名类型序列化为JSON,最常见的工具是 Json.NET .而且此代码非常简单:

However, there are ways to accomplish what you want to accomplish. First, you will need to serialize your anonymous type to JSON, the most common tool for this is Json.NET. And the code for this is pretty trivial:

var myContent = JsonConvert.SerializeObject(data);

接下来,您将需要构造一个内容对象来发送此数据,我将使用ByteArrayContent对象,但是如果需要,您可以使用或创建其他类型.

Next, you will need to construct a content object to send this data, I will use a ByteArrayContent object, but you could use or create a different type if you wanted.

var buffer = System.Text.Encoding.UTF8.GetBytes(myContent);
var byteContent = new ByteArrayContent(buffer);

接下来,您想要设置内容类型以使API知道这是JSON.

Next, you want to set the content type to let the API know this is JSON.

byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

然后,您可以使用内容形式发送与上一个示例非常相似的请求:

Then you can send your request very similar to your previous example with the form content:

var result = client.PostAsync("", byteContent).Result

另一方面,像在此处一样调用.Result属性可能会有一些

On a side note, calling the .Result property like you're doing here can have some bad side effects such as dead locking, so you want to be careful with this.

这篇关于如何将对象传递给HttpClient.PostAsync并序列化为JSON主体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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