我正在使用RestSharp来使用CapsuleCRM API。
当您POST以创建实体时,API不会在响应正文中返回任何内容,只会返回新创建的行的位置标题。
像这样:
http://developer.capsulecrm.com/v1/writing/
HTTP/1.1 201 Created
Location: https://sample.capsulecrm.com/api/party/1000
因此,如果RestSharp能够返回一个对象,它必须遵循该位置标题url,并从那里检索新对象,但这似乎不会发生。
这个问题类似于不同的问题,但不是重复的: RestSharp returns null value when response header has location field
更新 我已经发布了一个我提出的一个hacky解决方案作为答案,但默认情况下RestSharp真的没办法处理这个问题吗?
答案 0 :(得分:0)
我能够通过制作
的调整版本来完成这项工作public T Execute<T>(RestRequest request) where T : new()
方法,但它确实应该有更好的解决方案。
源代码: https://github.com/bjovas/CapsuleDotNet/blob/master/src/CapsuleDotNetWrapper/CapsuleApi.cs
public T CreateExecute<T>(RestRequest request) where T : new()
{
var client = new RestClient();
client.BaseUrl = BaseUrl;
client.Authenticator = new HttpBasicAuthenticator(_authtoken, "x");
var response = client.Execute<T>(request);
string locationUrl = (string)response.Headers.Where(h => h.Type == ParameterType.HttpHeader && h.Name == "Location").SingleOrDefault().Value;
int id;
if (int.TryParse(locationUrl.Remove(0, string.Format("{0}{1}", client.BaseUrl, request.Resource).Length), out id))
{
var secondRequest = new RestRequest();
secondRequest.Resource = locationUrl.Remove(0, string.Format("{0}", client.BaseUrl).Length);
secondRequest.RootElement = request.RootElement;
return Execute<T>(secondRequest);
}
else
throw new ApplicationException("Could not get ID of newly created row");
}