I've just updated my RestSharp application to 107.1.2 and are now unable to send post request. To test the problem I've set up a small express.js webserver to receive the requests from my C# application. On every post request I made, there is always no body available.
RestClientOptions options = new RestClientOptions("http://127.0.0.1:3000");
RestClient client = new RestClient(options);
RestRequest request = new RestRequest("api/test");
request.AddParameter("test1", "test1");
request.AddParameter("test2", "test2");
request.AddParameter("test3", "test3");
TestResponse response = await client.PostAsync<TestResponse>(request);
The code is based on the QueryString documentation https://restsharp.dev/usage.html#query-string. And yes, the params from the request I receive on the webserver are also empty. To test plain post request, I even tried the following:
RestClientOptions options = new RestClientOptions("http://127.0.0.1:3000");
RestClient client = new RestClient(options);
RestRequest request = new RestRequest("api/test");
const string json = "{ data: { foo: \"bar\" } }";
request.AddStringBody(json, ContentType.Json);
TestResponse response = await client.PostAsync<TestResponse>(request);
I can't find the problem why the requests are sent without an actual post body. In the previous version I've updated from, everything works fine.
Hope you can help me.
CodePudding user response:
Can you please Try this :
request.RequestFormat = DataFormat.Json;
request.AddJsonBody(new { A = "foo", B = "bar" });
or
const string json = "{ data: { foo: \"bar\" } }";
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
CodePudding user response:
RestClientOptions options = new RestClientOptions("http://127.0.0.1:3000");
var client = new RestSharp.RestClient(options);
var request = new RestSharp.RestRequest(RestSharp.Method.POST);
request.RequestFormat = RestSharp.DataFormat.Json;
request.AddHeader("Content-Type", "application/json");
const string json = "{ data: { foo: \"bar\" } }";
request.AddBody(JsonConvert.SerializeObject(json));
var response = client.Execute(request);
CodePudding user response:
Try this please
RestClientOptions options = new RestClientOptions("http://127.0.0.1:3000");
var restClient = new RestClient(options);
var restRequest = new RestRequest(Method.POST)
{
RequestFormat = DataFormat.Json
};
const string json = "{ data: { foo: \"bar\" } }";
request.AddBody(JsonConvert.SerializeObject(json));
var result = restClient.Post<TResponse>(restRequest);
if (!result.IsSuccessful)
{
throw new HttpException($"Item not found: {result.ErrorMessage}");
}
return result.Data;
