从标准 .NET rest 迁移到 RestSharp [英] Moving from standard .NET rest to RestSharp

查看:51
本文介绍了从标准 .NET rest 迁移到 RestSharp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For the most part, I have managed quite quickly to move my code from standard .NET code to using RestSharp. This has been simple enough for GET processes, but I'm stumped for POST processes

考虑以下内容

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,有没有一种特殊的方法必须这样做?我试过创建一个对象并使用

This is fairly straight forward to move across, except for the serialisation code. Is there a particular way this has to be done for RestSharp? I've tried creating an object and using

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

但服务器仍然返回错误.

but the server still comes back with an error.

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

I'm also currently using JSON.NET for deserialization to an error object when the user passes in bad data. Is there a way I can deserialize to error object based on a single string using RestSharp?

推荐答案

您已经接近了,但您无需担心使用 RestSharp 进行序列化.

You're close, but you don't need to worry about serialization with RestSharp.

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

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

By telling it that the format is JSON, then passing your already-serialized-as-JSON string, RestSharp is actually encoding it again as a string.

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

So you pass the string: {"firstName":"foo"} and it actually gets sent to the server as a JSON string object: "{\"firstName\":\"foo\"}" (note how your JSON is escaped as a string literal), which is why it's failing.

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

Note you can also use an anonymous object for the request:

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

<小时>

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


You use the same typed objects with the response (eg, RestSharp deserializes for you):

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

这篇关于从标准 .NET rest 迁移到 RestSharp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆