Search code examples
c#requestoauth-2.0restsharppayload

How to attach json-formatted payload into RestSharp request?


I can not put a workload in requests with RestSharp. Can anyone help me?

I tested

request.AddBody(payload) -> payload is a serialized object in json

But, doesn't work for me:

public override string Post(string url, object payload) { 
    RestRequest request = new RestRequest(url, Method.POST); 
    request.RequestFormat = DataFormat.Json;
    request.AddBody(payload); 
    IRestResponse response = Client.Execute(request); 
    return response.Content; 
} 

The return of method is empty string :/ :/


Solution

  • I have a helper method that I use:

        private IRestRequest CreateRequest(Uri uri, Method method, object body)
        {
            IRestRequest request = new RestRequest(uri, method);
            request.Resource = uri.ToString();
            request.Timeout = _timeout;
    
            if (body != null)
            {
                request.AddHeader("Content-Type", "application/json");
                request.RequestFormat = DataFormat.Json;
                request.JsonSerializer = new CustomConverter {ContentType = "application/json"};
                request.AddBody(body);
            }
    
            return request;
        }
    

    With the converter looking like this:

    class CustomConverter : ISerializer, IDeserializer
    {
        private static readonly JsonSerializerSettings SerializerSettings;
    
        static CustomConverter ()
        {
            SerializerSettings = new JsonSerializerSettings
            {
                DateTimeZoneHandling = DateTimeZoneHandling.Utc,
                Converters = new List<JsonConverter> { new IsoDateTimeConverter() },
                NullValueHandling = NullValueHandling.Ignore
            };
        }
    
        public string Serialize(object obj)
        {
            return JsonConvert.SerializeObject(obj, Formatting.None, SerializerSettings);
        }
    
        public T Deserialize<T>(IRestResponse response)
        {
            var type = typeof(T);
    
            return (T)JsonConvert.DeserializeObject(response.Content, type, SerializerSettings);
        }
    
        string IDeserializer.RootElement { get; set; }
        string IDeserializer.Namespace { get; set; }
        string IDeserializer.DateFormat { get; set; }
        string ISerializer.RootElement { get; set; }
        string ISerializer.Namespace { get; set; }
        string ISerializer.DateFormat { get; set; }
        public string ContentType { get; set; }
    }
    

    I can then call Execute on the returned request. I'm wondering whether the serialisation needs to be done by the RestSharp framework (by setting the serialiser to use).