如何将对象传递给HttpClient.PostAsync并序列化为JSON主体?

编程入门 行业动态 更新时间:2024-10-25 22:34:48
本文介绍了如何将对象传递给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.

推荐答案

您的问题的直接答案是:否. PostAsync 方法如下:

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主体?

本文发布于:2023-11-08 22:06:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1570578.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序列   如何将   主体   对象   PostAsync

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!