2021-11-12 乐帮网
c# netcore
升级到.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
关注我的微信公众号
在公众号里留言交流
投稿邮箱:1052839972@qq.com
庭院深深深几许?杨柳堆烟,帘幕无重数。
玉勒雕鞍游冶处,楼高不见章台路。
雨横风狂三月暮。门掩黄昏,无计留春住。
泪眼问花花不语,乱红飞过秋千去。
如果感觉对您有帮助
欢迎向作者提供捐赠
这将是创作的最大动力