public string Post(T obj)
{
HttpRequestMessage request = new HttpRequestMessage();
MediaTypeFormatter[] formatter = new MediaTypeFormatter[] { new JsonMediaTypeFormatter() };
var content = request.CreateContent<T>(obj, MediaTypeHeaderValue.Parse("application/json"), formatter, new FormatterSelector());
HttpResponseMessage response = client.PostAsync(this.url, content).Result;
return response.Content.ToString();
}
这是我的方法Post,我在HTTPClient
中使用,但有一个问题 - CreateContent
和FormatterSelector
- 来自旧引用的类。如何将此代码重写为最新引用:
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using Newtonsoft.Json;
我明白什么问题。这种方法是扩展方法!所以我们无法使用它们。
答案 0 :(得分:2)
你可以尝试这段代码:
public async Task<string> Post<T>(T obj)
{
MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
HttpContent content = new ObjectContent<T>(obj, jsonFormatter);
var response = await client.PostAsync(this.Url, content);
return response.Content.ToString();
}