从标准.NET rest迁移到RestSharp

时间:2013-07-16 21:21:48

标签: c# restsharp

在大多数情况下,我已经很快将代码从标准.NET代码移动到使用RestSharp。这对于GET进程来说已经足够简单了,但我对POST进程感到难过

考虑以下

var request = System.Net.WebRequest.Create("https://mytestserver.com/api/usr") as System.Net.HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json;version=1";
request.Headers.Add("Content-Type", "application/json;version=1");
request.Headers.Add("Accepts", "application/json;version=1");
request.Headers.Add("Authorize", "key {key}");
using (var writer = new System.IO.StreamWriter(request.GetRequestStream())) {
  byte[] byteArray = System.Text.Encoding.UTF8.GetBytes("{\n    \"firstName\": \"Dan\",\n    \"lastName\": \"Eccles\",\n    \"preferredNumber\": 1,\n    \"email\" : \"testuser@example.com\",\n    \"password\": \"you cant get the wood\"\n}");
  request.ContentLength = byteArray.Length;
  writer.Write(byteArray);
  writer.Close();
}
string responseContent;
using (var response = request.GetResponse() as System.Net.HttpWebResponse) {
using (var reader = new System.IO.StreamReader(response.GetResponseStream())) {
  responseContent = reader.ReadToEnd();
}

除了序列化代码之外,这是相当直接的。有什么特别的方法可以为RestSharp做这个吗?我试过创建一个对象并使用

var json = JsonConvert.SerializeObject(user);
restRequest.RequestFormat = DataFormat.Json;
restRequest.AddBody(json);

但服务器仍然返回错误。

当用户传入错误数据时,我目前还在使用JSON.NET对错误对象进行反序列化。有没有办法可以使用RestSharp基于单个字符串反序列化为错误对象?

1 个答案:

答案 0 :(得分:7)

你很接近,但你不必担心使用RestSharp进行序列化。

var request = new RestRequest(...);
request.RequestFormat = DataFormat.Json;
request.AddBody(user);  // user is of type User (NOT string)

通过告诉它格式为JSON,然后传递已经序列化的JSON字符串,RestSharp实际上将再次编码为字符串

所以你传递了字符串:{"firstName":"foo"},它实际上作为 JSON字符串对象发送到服务器:"{\"firstName\":\"foo\"}"(注意你的JSON如何作为字符串转义文字),这就是它失败的原因。


请注意,您还可以为请求使用匿名对象:

var request = new RestRequest(...);
request.RequestFormat = DataFormat.Json;
request.AddBody(new{ 
    firstName = "Dan",
    lastName = "Eccles",
    preferredNumber = 1,
    // etc..
  });

您在响应中使用相同的类型对象(例如,RestSharp为您反序列化):

var response = client.Execute<UserResponse>(request);
// if successful, response.Data is of type UserResponse