WebApi当道的今天,之前要自己写的序列化,现在有人都做好了
public class PostHelper { static HttpClient client = new HttpClient(); public static async Task<T> PostTestAsync<T>(string url,T args) { //string json = JsonSerializer.Serialize(args); //HttpContent content = new StringContent(json,Encoding.UTF8); //content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue ("application/json"); //HttpResponseMessage response = await client.PostAsync(url, content); HttpResponseMessage response = await client.PostAsJsonAsync(url, args); response.EnsureSuccessStatusCode(); // Deserialize the updated product from the response body. var result = await response.Content.ReadAsAsync<T>(); return result; } }
对于倒数第二行,可以会有以下错误提示
“System.Net.Http.HttpContent”不包含“ReadAsAsync”的定义
对于Net4.X,可以添加以下引用
System.Net.Http.Formatting
对于net6.0,添加以下包
Microsoft.AspNet.WebApi.Client
本文只发布在博客园,请勿转载!
标签:ReadAsAsync,Http,System,Net,HttpContent,response From: https://www.cnblogs.com/kevin-Y/p/17903641.html