尝试使用RestSharp创建一个通用方法来调用REST端点,我遇到的唯一问题是将内容作为动态返回。
Response.Data为null,Response.Content始终为字符串。我希望返回值至少是一个匿名类型。
public T Call<T>(string url, Method method = Method.GET, ResponseType type = ResponseType.JSON, params Parameter[] parameters)
{
var request = new RestRequest(url, method);
switch (type)
{
case ResponseType.JSON:
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Accept", "application/json");
request.RequestFormat = DataFormat.Json;
break;
case ResponseType.XML:
request.AddHeader("Content-Type", "application/xml");
request.AddHeader("Accept", "application/xml");
request.RequestFormat = DataFormat.Xml;
break;
}
foreach (var parameter in parameters)
request.AddParameter(parameter);
var response = _client.Execute<dynamic>(request);
if (!string.IsNullOrEmpty(response.ErrorMessage) || response.ErrorException != null)
throw new System.Exception(response.ErrorMessage, response.ErrorException);
return response.Data;
}
答案 0 :(得分:0)
鉴于你有类型T,你不能这样做:
var response = _client.Execute<T>(request);