7407

Moving from standard .NET rest to RestSharp

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

Consider the following

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(); }

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.

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?

Answer1:

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)

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.

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.

<hr>

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.. }); <hr>

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

Recommend

  • How to Post a form through c#
  • google URL shortener API error (403 forbidden) [update]
  • Direct Uploading New Ftp listbox Lines
  • Powershell - Replace first occurences of String
  • How can i convert WriteableBitmap to jpg or some other common format?
  • Out of Memory Exception - Reading large text file for HttpWebRequest
  • SWIG get returntype from String as String array in java
  • Two header with same name in include path
  • Object de-serializing from base64 in C#
  • (Python 3) How to pass binary file as text without saving first
  • How to avoid OutOfMemoryException while loading large chunks of data from a database?
  • The process cannot access the file because it is being used by another process
  • How to add header line to CSV without loading whole file?
  • How to send image as base64 string in JSON using HTTP POST in Android?
  • networkstream “cannot access a disposed object” when using newly created networkstream
  • Searching Persian characters and words in SQL server with different encoding
  • Complicated COUNT query in MySQL
  • css font-size and line-height not matching the baseline
  • Graceful pod termination
  • insert a picture into database(sqlite) with java code. what should i do?
  • Getting error java.io.FileNotFoundException (log4j log file) at the time of publish project on cloud
  • Getting NullPointer exception with File.listfiles()
  • How to make JSON.NET deserialize to Microsoft Date Time?
  • Convert Type Decimal to Hex (string) in .NET 3.5
  • copying resource to sdcard gives a damaged file in android
  • Encrypt data by using a public key in c# and decrypt data by using a private key in php
  • SSO with signing and signature validation doesn't work
  • MySQL WHERE-condition in procedure ignored
  • Deserializing XML into class C#
  • How do you troubleshoot character encoding problems?
  • Web-crawler for facebook in python
  • How to format a variable of double type
  • VB.net deserialize, JSON Conversion from type 'Dictionary(Of String,Object)' to type '
  • trying to dynamically update Highchart column chart but series undefined
  • How can I get HTML syntax highlighting in my editor for CakePHP?
  • How do I configure my settings file to work with unit tests?
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • costura.fody for a dll that references another dll
  • Binding checkboxes to object values in AngularJs
  • java string with new operator and a literal