在大多数情况下,我很快就将我的代码从标准 .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 基于单个字符串反序列化为错误对象?