升级到.Net5后HttpClient多了一些扩展方法,
命名空间:
System.Net.Http.Json
程序集:
System.Net.Http.Json.dll
签名如下:
public static System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PostAsJsonAsync<TValue> (this System.Net.Http.HttpClient client, string? requestUri, TValue value, System.Threading.CancellationToken cancellationToken);
public static System.Threading.Tasks.Task<object?> GetFromJsonAsync (this System.Net.Http.HttpClient client, string? requestUri, Type type, System.Threading.CancellationToken cancellationToken = default);
public static System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> PutAsJsonAsync<TValue> (this System.Net.Http.HttpClient client, string? requestUri, TValue value, System.Threading.CancellationToken cancellationToken);
其中我试用了GetFromJsonAsync ,正如我认为的那样,并没有发现什么问题,使用方法如下:
var response = await httpClient.GetFromJsonAsync<mymodel>(url);
这里重点说一下PostAsJsonAsync,用它来提交数据的示例:
HttpClient httpClient = new HttpClient();
string url1 = @"https://lebang2020.cn/api/siteinfo";
var postArgs = new { VIN = "00152F3B1895355561317EAEAFD778843C864520" };
var response = await httpClient.PostAsJsonAsync(url1, postArgs);
if (response.IsSuccessStatusCode)
{
var resStr = await response.Content.ReadAsStringAsync();
}
上面代码足矣。还有以下几种示例:
HttpClient httpClient = new HttpClient();
string url1 = @"https://lebang2020.cn/api/siteinfo";
var postArgs = new { VIN = "00152F3B1895355561317EAEAFD778843C864520" };
var source = new CancellationTokenSource();
var response = await httpClient.PostAsJsonAsync(url1, postArgs, source.Token);
if (response.IsSuccessStatusCode)
{
var resStr = await response.Content.ReadAsStringAsync();
}
或者以下写法:
HttpClient httpClient = new HttpClient();
string url1 = @"https://lebang2020.cn/api/siteinfo";
var postArgs = new { VIN = "00152F3B1895355561317EAEAFD778843C864520" };
var source = new CancellationTokenSource();
var postContent = JsonContent.Create(postArgs);
await postContent.LoadIntoBufferAsync();
var response = await httpClient.PostAsJsonAsync(url1, postContent, source.Token);
if (response.IsSuccessStatusCode)
{
var resStr = await response.Content.ReadAsStringAsync();
}
最后说一下它的代替方案:以上方法只能用于.Net 5及以上版本,下面这个可以用到.Net Core 3中
HttpClient httpClient = new HttpClient();
string url1 = @"https://lebang2020.cn/api/siteinfo";
var postArgs = new { VIN = "00152F3B1895355561317EAEAFD778843C864520" };
var response = await httpClient.PostAsync(url1, new StringContent(JsonConvert.SerializeObject(postArgs), Encoding.UTF8, "application/json"));
if (response.IsSuccessStatusCode)
{
//other code ....
}
lebang2020.cn