c# - 从通用助手返回 HttpResponseMessage
问题描述
当没有异常时,如何在 Helper 类中创建以下方法以在以下代码块中返回 HttpResponseMessage:
public class HttpClientHelper
{
public static T PutAsync<T>(string resourceUri, object request)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(resourceUri);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
var responseMessage = client.PutAsJsonAsync(resourceUri, request).Result;
return new HttpResponseMessage // It says cannot implicitly convert to Type T
{
StatusCode = responseMessage.StatusCode,
Content= responseMessage.Content.ReadAsStringAsync().Result.ToString()
};
}
catch (Exception ex)
{
throw new HttpResponseException(ex.Message.ToString());
}
}
}
}
HttpResponse 异常:
public class HttpResponseException : Exception
{
private string _message;
public HttpResponseException() : base() { }
public HttpResponseException(string message) : base(message)
{
this._message = message;
}
public override string Message
{
get
{
return this._message;
}
}
}
我正在尝试实现一个通用帮助器类来调用我的 ASP.NET Web Api。
解决方案
不返回HttpResponseMessage
,而是返回 Web Api 返回的反序列化对象:
public static T PutAsync<T>(string resourceUri, object request)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(resourceUri);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
var responseMessage = client.PutAsJsonAsync(resourceUri, request).Result;
responseMessage.EnsureSuccessStatusCode();
var responseData = responseMessage.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<T>(responseData);
}
catch (Exception ex)
{
throw new HttpResponseException(ex.Message);
}
}
}
此外,PutAsync
让我觉得我正在使用一种async Task
方法。要么调用它,Put
要么让它异步。
推荐阅读
- java - 从 OpenCV 中的 Mat 对象填充二维数组时出现 NullPointerException
- windows - Powershell 脚本在第一次执行时不运行
- go - 如何使用 delve 调试器单步执行可执行文件?
- c# - 如何在另一个移动瓷砖的末端实例化一个瓷砖?
- express - 在 heroku 上使用 express 和 webpack 配置运行 prod 服务器
- spring - Spring MVC:将请求参数绑定到通用列表
- python - 循环遍历数据框列表以动态创建新列
- python-3.x - Django 静态文件保存在意外位置
- php - 以编程方式将 Woocommerce 购物车项目从虚拟更改为物理
- r - 如何将标签放入集群中?