0
votes

I have a problem with post request with RestSharp. I have 2 classes:

public class UnitToPost
        {
            public bool floating_point { get; set; }
            public Dictionary<string, TranslationUnitToPost> translations { get; set; }
        }

        public class TranslationUnitToPost
        {
            public string name { get; set; }
        }

And I want to send it with post request:

        client = new RestClient(adresApi);

        client.AddDefaultHeader("Authorization", "Bearer " + key);           

        IRestRequest updateProduct = new RestRequest("units", Method.POST);

        ShoperModel.UnitToPost unitToPost = new ShoperModel.UnitToPost();
        unitToPost.floating_point = true;
        ShoperModel.TranslationUnitToPost transUnit = new ShoperModel.TranslationUnitToPost();
        transUnit.name = "namename";
        unitToPost.translations = new Dictionary<string, ShoperModel.TranslationUnitToPost>();
        unitToPost.translations.Add("pl_PL", transUnit);


        updateProduct.RequestFormat = RestSharp.DataFormat.Json;
        updateProduct.AddBody(unitToPost);

        IRestResponse updateProductResponse = this.client.Execute(updateProduct);

And I always get an error:

[RestSharp.RestResponse] = "StatusCode: InternalServerError, Content-Type: application/json, Content-Length: -1)"

Content = "{\"error\":\"server_error\",\"error_description\":\"Operation Failed\"}"

What is the cause of it? Could it be because of Dictionary in my class?

1

1 Answers

0
votes

I've run your code and it issues a request with a valid JSON body.

POST http://..../units HTTP/1.1

Accept: application/json,application/xml, text/json, text/x-json, text/javascript, text/xml Authorization: Bearer a

User-Agent: RestSharp/105.2.3.0

Content-Type: application/json

Host: .....

Content-Length: 84

Accept-Encoding: gzip, deflate

Connection: Keep-Alive

{"floating_point":true,"translations":[{"Key":"pl_PL","Value":{"name":"namename"}}]}

It looks like the problem may be with the receiving server. If you're not doing so already I'd suggest running Fiddler (http://www.telerik.com/fiddler) and inspecting the request/response.

Edit...

I only just realised you want the JSON body to be :- {"floating_point":true,"translations":{"pl_PL":{"name":"namename"}}}

I did find a RestSharp issue that covers this :- https://github.com/restsharp/RestSharp/issues/696

This includes a post where someone has used an ExpandoObject to get the required result.

http://theburningmonk.com/2011/05/idictionarystring-object-to-expandoobject-extension-method/

However, I found it easier to use JSON .NET to serialise and set the body with the following code:-

updateProduct.AddBody(JsonConvert.SerializeObject(unitToPost));