Reputation:
I am using RestSharp for API calling, but when I post data, I get an internal server error. Here is my code. Content is a generic model which I am passing.
private async Task<Message<T>> PostAsyncRestSharp<T>(Uri requestUrl, T content)
{
try
{
var client = new RestClient(requestUrl.ToString());
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", content, ParameterType.RequestBody);
IRestResponse response = await client.ExecuteAsync(request);
var resp = response.Content;
return JsonConvert.DeserializeObject<Message<T>>(resp);
}
catch (Exception ex)
{
throw;
}
}
It doesn't even hit the catch block.
GET CALL
Get call is working fine
private async Task<T> GetAsyncRestSharp<T>(Uri requestUrl, string urlParams)
{
var client = new RestClient($"{requestUrl}?{urlParams}");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddParameter("text/plain", "", ParameterType.RequestBody);
IRestResponse response = await client.ExecuteAsync(request);
var resp = response.Content;
return JsonConvert.DeserializeObject<T>(resp);
}
Upvotes: 0
Views: 3316
Reputation: 61
According to the RestSharp docs you should use .AddJsonBody method
We recommend using AddJsonBody or AddXmlBody methods instead of AddParameter with type BodyParameter. Those methods will set the proper request type and do the serialization work for you.
When you call AddJsonBody, it does the following for you:
- Instructs the RestClient to serialize the object parameter as JSON when making a request
- Sets the content type to application/json
- Sets the internal data type of the request body to DataType.Json
https://restsharp.dev/usage/parameters.html#request-body
Your code doesn't work because you're sending T object without serialization.
Upvotes: 1