gpt4 book ai didi

c# - 使用HttpClient.GetFromJsonAsync(),如何处理基于HttpStatusCode的HttpRequestException而无需额外的SendAsync调用?

转载 作者:行者123 更新时间:2023-12-03 17:04:12 33 4
gpt4 key购买 nike

System.Net.Http.JsonHttpClient扩展方法(例如GetFromJsonAsync())极大地简化了从Web API检索json对象的例程代码。使用起来很愉快。
但是由于它的设计方式(直接返回反序列化的对象),它不会产生任何HttpResponseMessage进行检查,因此我无法根据HttpStatusCode采取自定义操作。
相反,非成功状态代码将导致HttpRequestException,它似乎没有提供任何暴露强类型HttpStatusCode的属性。相反,状态代码包含在异常的Message字符串本身中。
编辑:.NET 5.0添加了HttpRequestException.StatusCode属性,因此现在可以在调用GetFromJsonAsync时对其进行检查。
//下面的旧帖子
所以我一直在做这样的事情:

try
{
var cars = await httpClient.GetFromJsonAsync<List<Car>>("/api/cars");
//...
}

catch (HttpRequestException ex)
{
if (ex.Message.Contains(HttpStatusCode.Unauthorized.ToString()))
{
//Show unauthorized error page...
}
//...
}
这感觉有点hacky。通过创建 HttpRequestMessage和调用 SendAsync的传统方法,我们自然有机会检查响应的 HttpResponseMessage.StatusCode。将其中一些代码加回去会破坏在 System.Net.Http.Json中使用单行代码的便利目的。
这里的任何建议将不胜感激。

最佳答案

您可以使用:

// return HttpResponseMessage
var res= await httpClient.GetAsync<List<Car>>("/api/cars")

if (res.IsSuccessStatusCode)
var cars = res.Content.ReadFromJsonAsync<List<Car>>();
else
// deal with the HttpResponseMessage directly as you used to
我使用这样的基类:
using System;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;


namespace MyProject.ClientAPI
{
public abstract class ClientAPI
{
protected readonly HttpClient Http;
private readonly string BaseRoute;

protected ClientAPI(string baseRoute, HttpClient http)
{
BaseRoute = baseRoute;
Http = http;
}

protected async Task<TReturn> GetAsync<TReturn>(string relativeUri)
{
HttpResponseMessage res = await Http.GetAsync($"{BaseRoute}/{relativeUri}");
if (res.IsSuccessStatusCode)
{
return await res.Content.ReadFromJsonAsync<TReturn>();
}
else
{
string msg = await res.Content.ReadAsStringAsync();
Console.WriteLine(msg);
throw new Exception(msg);
}
}

protected async Task<TReturn> PostAsync<TReturn, TRequest>(string relativeUri, TRequest request)
{
HttpResponseMessage res = await Http.PostAsJsonAsync<TRequest>($"{BaseRoute}/{relativeUri}", request);
if (res.IsSuccessStatusCode)
{
return await res.Content.ReadFromJsonAsync<TReturn>();
}
else
{
string msg = await res.Content.ReadAsStringAsync();
Console.WriteLine(msg);
throw new Exception(msg);
}
}
}
}
然后从派生类开始,我们回到单线
public class MySpecificAPI : ClientAPI
{
public MySpecificAPI(HttpClient http) : base("api/myspecificapi", http) {}

public async Task<IEnumerable<MyClass>> GetMyClassAsync(int ownerId)
{
try
{
return GetAsync<IEnumerable<MyClass>>($"apiMethodName?ownerId={ownerId}");
}
catch (Exception e)
{
// Deal with exception
}
}

// repeat for post
}
更新:处理空返回
在遇到WebAPI返回null的有效情况后,以下行:
return await res.Content.ReadFromJsonAsync<TReturn>();
将抛出Json反序列化错误。
为了解决这个问题,我们需要检测NoContent响应(204)并进行相应的处理:
if (res.StatusCode == HttpStatusCode.NoContent)
return default(TReturn);
else if (res.IsSuccessStatusCode)
return await res.Content.ReadFromJsonAsync<TReturn>();

关于c# - 使用HttpClient.GetFromJsonAsync(),如何处理基于HttpStatusCode的HttpRequestException而无需额外的SendAsync调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65383186/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com