“System.Net.Http.HttpContent”不包含“ReadAsAsync”的定义

发布时间 2023-12-15 16:31:58作者: 生命体验之kevin-Y

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