RestSharp portable add json body from userinput field - c#

in my UWP App, the user can enter a json body in a textfield and set it as body in a POST Rest-Request via restsharp portable.
So the user types this into a textbox (value is bound to requestBody):
{ "string": "Hello World"}
and then I add the string to the request:
request.AddParameter("application/json; charset=utf-8", requestBody, ParameterType.RequestBody);
The body was added, but not correct.
The Server doesn´t parse the incoming json body.
I don´t know what´s the problem, but I think some characters a not encoded correctly.
Has anyone managed it to add a json body in this way?
This solution works:
var b = JsonConvert.DeserializeObject<Object>(requestBody);
request.AddJsonBody(b);
but that´s not the clean way

Example of code that has worked for me:
var client = new RestClient("http://localhost");
var request = new RestRequest("pathtoservice", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddParameter("application/json", "{ \"Some\": \"Data\" }", ParameterType.RequestBody);
var result = client.Execute(request);
For completeness, when using the RestSharp Portable the above would be:
var client = new RestClient("http://localhost");
var request = new RestRequest("pathtoservice", Method.POST);
var requestBody = Encoding.UTF8.GetBytes("{ \"Some\": \"Data\" }");
request.AddParameter("application/json; charset=utf-8", requestBody, ParameterType.RequestBody);
var result = client.Execute(request);

Related

Sending parameter request with RestSharp in C#. Getting Error: Required field \"expr\" missing in JSON body

I am writing a simple calculation machine application in Windows Form application. I want to perform operations using math js web api (post), but where I call api I get this error:
Error: Required field \"expr\" missing in JSON body" // in Response
My code is here :
private void Equals_Click(object sender, EventArgs e)
{
var client = new RestClient("http://api.mathjs.org/v4/");
var request = new RestRequest("/expr", Method.POST);
var deger = txtCevap.Text; // txtCevap.Text is my calculator parameter
var json = JsonConvert.SerializeObject(deger);
request.AddParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;
IRestResponse response = client.Execute(request);
}
Can you help me in this topic? Thanks.
for api.mathjs.org, you are required to pass string or string[] with expr element. Please review their requirements here.
var client = new RestClient("http://api.mathjs.org/v4/");
var request = new RestRequest("", Method.POST);
var deger = #"{""expr"": ""2+1""}"; // txtCevap.Text is my calculator parameter
request.AddJsonBody(deger);
request.RequestFormat = DataFormat.Json;
IRestResponse response = client.Execute(request);
response object's content looks like below that you can easily deserialize. they always have Result and Error.
"{\"result\":\"3\",\"error\":null}"
dynamic result = JsonConvert.DeserializeObject(response.Content);
string answer = result["result"].ToString()

Use RestSharp Post Object as JSON and read it from the other side of the call

I have a C# REST Web API and I have some code like this that makes a request to an endpoint. Some of the data that I want to pass along is an object of my own type and since it is a complex object, I would like to pass it using POST.
RestClient client = new RestClient(Constants.Endpoints.serviceEndPoint)
{
Timeout = 1000
};
string requestResource = Constants.Endpoints.apiEndPoint;
RestRequest request = new RestRequest(requestResource, Method.POST);
request.AddParameter("Authorization", $"Bearer {accessToken}", ParameterType.HttpHeader);
request.AddHeader("Accept", "application/json");
request.AddParameter("id", id, ParameterType.UrlSegment);
request.AddParameter("text/json", objectIWantToSerialize, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
On the other side, I am trying to read the object itself with some code like this
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
foreach (var content in provider.Contents)
{
// what should I do here to read the content as a JSON
// and then transform it as the object it used to be before the call?
}
I tried to do await content.ReadAsJsonAsync< MyType>(); but also tried await content.ReadAsStringAsync(); and none of these worked. Am I doing something wrong at the time I execute in the client? Or is it something that I am doing on the other side while reading the content?
Instead of this line:
request.AddParameter("text/json", objectIWantToSerialize, ParameterType.RequestBody);
You should use the .AddBody(object) method.
So you're code would look like this:
RestRequest request = new RestRequest(requestResource, Method.POST);
//add other headers as needed
request.RequestFormat = DataFormat.Json;
request.AddBody(objectIWantToSerialize);
IRestResponse response = client.Execute(request);
On the server, if you're using MVC/WebAPI, you can just put the C# type as the input and ASP.NET will deserialize it for you. If not, can you provide more context about how you're receiving the request?

request webapi with restharp

Goodmorning everyone,
using postan I make a request as in the figure, and I get data.
I write using the same call (at least I assume) and it returns an empty string and not a json.
Where could it be the mistake?
Thank you all
var client = new RestClient("http://pp.miosito.it/API/");
var request = new RestRequest("STHQRY", Method.POST);
// request.RequestFormat = DataFormat.Json;
request.AddParameter("TblName", "STSIG$");
var response = client.Execute(request);
var content = response.Content;
enter image description here
Query Parameter Detail is mentioned in add Parameter. Please change the code as below
Code:
var client = new RestClient("http://pp.miosito.it/API/");
var request = new RestRequest("STHQRY?TblName=STSIG$", Method.POST);
//Request Body detail needs to be added.
//I assumed input is JSON. Please change the header part , if the body has different
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", body, ParameterType.RequestBody);
var response = client.Execute(request);
var content = response.Content;

Why is RestSharp AddHeader("Accept", "application/json"); = to a list of item?

I've got this Windows Phone 8 project in C#, where I'm using RestSharp 104.4.0 to make a request to a server. The server only accepts a "Accept" type of "application/json". My code to call the request:
var client = new RestClient(_jsonBaseUrl + someURL)
{
Authenticator = new HttpBasicAuthenticator(someUsername, somePassword)
};
var request = new RestRequest(Method.POST);
UTF8Encoding utf8 = new UTF8Encoding();
byte[] bytes = utf8.GetBytes(json);
json = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Accept", "application/json");
request.AddBody(json);
request.Parameters.Clear();
request.AddParameter("application/json", json, ParameterType.RequestBody);
client.ExecuteAsync<UserAccount>(request, response =>
{
if (response.ResponseStatus == ResponseStatus.Error)
{
failure(response.ErrorMessage);
}
else
{
success("done");
}
});
the "json" variable is a JSON string.
As you can see i've set my accept type to AddHeader("Accept", "application/json"); But for some wired reason the server receives this as accept type:
"Accept": "application/json, application/xml, text/json, text/x-json, text/javascript, text/xml"
What do i have to do, to make sure the only accept type the server gets is "Accept": "application/json"?
Any kind of help would be much appreciated.
From https://groups.google.com/forum/#!topic/restsharp/KD2lsaTC0eM:
The Accept header is automatically generated by inspecting the
"handlers" that are registered with the RestClient instance. One optin
is to use RestClient.ClearHandlers (); and then add back explicitly
the JSON deserializer with RestClient.AddHandler("application/json",
new JsonDeserializer ());

Server is not Recognizing the json, sending request using restSharp

i am trying to post some json to jboss services. using restSharp.. my code is as follows.
RestClient client = new RestClient(baseURL);
RestRequest authenticationrequest = new RestRequest();
authenticationrequest.RequestFormat = DataFormat.Json;
authenticationrequest.Method = Method.POST;
authenticationrequest.AddParameter("text/json", authenticationrequest.JsonSerializer.Serialize(prequestObj), ParameterType.RequestBody);
and also tried this one
RestClient client = new RestClient(baseURL);
RestRequest authenticationrequest = new RestRequest();
authenticationrequest.RequestFormat = DataFormat.Json;
authenticationrequest.Method = Method.POST; authenticationrequest.AddBody(authenticationrequest.JsonSerializer.Serialize(prequestObj));
but in both cases my server is giving me error that json is not in correct format
Try using JsonHelper to prepare your json as the following
string jsonToSend = JsonHelper.ToJson(prequestObj);
and then
authenticationrequest.AddParameter("application/json; charset=utf-8", jsonToSend, ParameterType.RequestBody);
I have found what was going wrong...
i am using RestSharp in windows metro Style, so downloaded source code and make some modifications... so that modifications in the function PutPostInternalAsync i just added this modifications
httpContent = new StringContent(Parameters[0].Value.ToString(), Encoding.UTF8, "application/json");
and it solve the problem....
Parameters[0].Value.ToString() instead of this you can write a method which can return the serialize json object. (as string).

Categories