C# httpclient 泛型封装异常返回值
时间: 2023-09-27 21:11:38 浏览: 265
在 C# 中,你可以使用泛型方法为 HttpClient 封装异常处理和返回值。以下是一个示例代码:
```csharp
public async Task<T> GetAsync<T>(string url)
{
try
{
using (var client = new HttpClient())
{
var response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(json);
}
}
catch (HttpRequestException ex)
{
throw new Exception("请求失败", ex);
}
catch (Exception ex)
{
throw new Exception("请求异常", ex);
}
}
```
在上面的代码中,我们使用了 async/await 异步编程模式来发送 HTTP 请求,并使用 HttpClient 的 EnsureSuccessStatusCode 方法来确保请求成功。如果请求失败,我们通过抛出自定义的异常来返回错误信息。如果发生其他异常,也会抛出自定义异常。
使用示例:
```csharp
try
{
var result = await GetAsync<MyModel>("http://example.com/api/mymodel");
// 处理返回值 result
}
catch (Exception ex)
{
// 处理异常 ex
}
```
在使用时,你可以将泛型参数指定为你期望的返回类型,例如 MyModel。当出现异常时,将抛出自定义异常,并且你可以在 catch 语句块中处理它。
阅读全文
相关推荐


















