I want to make a POST request to a URL like this:
http://localhost/resource?auth_token=1234
And I want to send JSON in the body. My code looks something like this:
var client = new RestClient("http://localhost");
var request = new RestRequest("resource", Method.POST);
request.AddParameter("auth_token", "1234");
request.AddBody(json);
var response = client.Execute(request);
How can I set the auth_token parameter to be a GET parameter and make the request as POST?
The current version of RestSharp has a short method that makes use of a template:
var request = new RestRequest("resource?auth_token={token}", Method.POST);
request.AddUrlSegment("token", "1234");
Alternatively, you can add a parameter without a template:
var request = new RestRequest("resource", Method.POST);
request.AddQueryParameter("auth_token", "1234);
or
var request = new RestRequest("resource", Method.POST);
request.AddParameter("auth_token", "1234", ParameterType.QueryString);
This should work if you 1) add the token to the resource url and 2) specify ParameterType.UrlSegment like this:
var client = new RestClient("http://localhost");
var request = new RestRequest("resource?auth_token={authToken}", Method.POST);
request.AddParameter("auth_token", "1234", ParameterType.UrlSegment);
request.AddBody(json);
var response = client.Execute(request);
This is far from ideal - but the simplest way I've found... still hoping to find a better way.
Related
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.
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");
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);
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;
I am having trouble understanding why do you think the request is made without the body. I would expect that the express API gives you no body, but it doesn't mean the request has no body.
I traced your requests, and you can see them here.
The first snippet produces the following request:
As you can see it has the correct content type and the body is correctly formed as form URL encoded body content.
Your second snippet also produces the correct request with JSON body:
It is impossible to say why your server doesn't understand these requests, as you haven't specified what the server needs, but I don't see any issues with those requests per se.
If you you want to add parameters in the request use below way:
RestClient client = new("http://127.0.0.1:3000");
RestRequest restRequest = new("api/test");
restRequest.AddParameter("test1", "test1");
request.AddParameter("test2", "test2");
request.AddParameter("test3", "test3");
RestResponse response = client.ExecuteAsync(restRequest,Method.Post).Result;
Assert.AreEqual(HttpStatusCode.OK, response);
If you you want to add json body in the request use the below way:
RestClient client = new("http://127.0.0.1:3000");
RestRequest restRequest = new("api/test");
string requestBody= "{\"data\":{\"foo\":\"bar\"}}"
restRequest.AddStringBody(requestBody, DataFormat.Json);
RestResponse response = client.ExecuteAsync(restRequest, Method.Post).Result;
Assert.AreEqual(HttpStatusCode.OK, response);
I am new to WEB API and I have created a get and a post method the get is working however the the parameter in the post is returning null.
The code for request is
if (ModelState.IsValid)
{
var client = new RestClient(string.Format("{0}/api/order/createorder",Baseurl));
client.Timeout = -1;
var request = new RestRequest(Method.POST);
var test = JsonConvert.SerializeObject(order);
request.AddJsonBody(order);
IRestResponse response = client.Execute(request);
and it points to the following method
[HttpPost]
[Route("api/order/createorder")]
public HttpResponseMessage AddOrder([FromBody]IOrder order)
{
if(order== null)
{
var resp = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent("The order is a required parameter"),
ReasonPhrase = "Order not present"
};
throw new HttpResponseException(resp);
}
I have added the <requestLimits maxAllowedContentLength="4294967295" /> to the web config but to no avail.
Can anyone point me to what I am doing wrong with the request?
Cheers
Try this code
var client = new RestClient(string.Format("{0}/api/order/createorder",Baseurl));
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json; charset=utf-8");
var body = JsonConvert.SerializeObject(order);
request.AddParameter("application/json; charset=utf-8", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var result = response.Content;
and never use interfaces in action parameters, since the action needs to create an object, but it is impossible from interface
[Route("~/api/order/createorder")]
public HttpResponseMessage AddOrder([FromBody] Order order)
I think if can rewrite you request to this ->
var client = new RestClient("/api/order/createorder",Method.Post, DataFormat.Json);
client.AddJsonBody(order);
IRestResponse response = client.Execute(request);
That might just work, you may need some mapping potentially if the payload you are passing to the controller is a different type.
I have a question about making an authorized call to a GET Url using RestSharp.
I have a provided basic token, which looks something like this: dGVzdG5hbWU6dGVzdHBhc3N3b3Jk.
Let's say the GET Url is: https://sometest.api.com/todos?id=1 and requires authorization.
How would I pass the above token in the above GET Url?
I tried this:
var client = new RestClient("https://sometest.api.com") // base address
var request = new RestRequest("todos?id=1"); // resource
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Basic dGVzdG5hbWU6dGVzdHBhc3N3b3Jk");
var response = client.Execute(request);
This does not seem to work. Do I need to add the basic token as a parameter instead, or both in the header and as parameter?
Or would I need to use the client.Authenticator on the RestClient:
client.Authenticator = new HttpBasicAuthenticator("testname", "testpassword");
Any help is appreciated, thanks.
Best Regards
Could you provide more information how did you conclude that it does not work? Any exception? An error message you could provide?
How did you get that token? What the expiration time of the token?
This is how I am doing it, pretty much like you, except I am using different token type:
var request = CreateServerRequest(_configuration.SOME_URI);
request.AddHeader("Authorization", $"Bearer {Token}");
request.AddJsonBody(request);
var server = new RestClient(_configuration.SOME_ENDPOINT);
var serverResponse = server.Execute(request);
if (serverResponse.StatusCode == HttpStatusCode.OK)
{
return new ServiceResponse<bool>(true);
}
Where the method CreateServerRequest contains only:
return new RestRequest(uri)
{
RequestFormat = DataFormat.Json,
Method = Method.POST
};
Hope this helps,
Cheers and happy coding.
I am using RestSharp to post some data to a url. I am monitoring this operation using fiddler. when I use Simple .net HttpClient with this code:
using (var client = new HttpClient())
{
var values = new Dictionary<string, string> {
{ "par1", "1395/11/29" },
{ "par2", "2" }};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://someurl.com/resource", content);
var responseString = await response.Content.ReadAsStringAsync();
}
every thing is good and this return true result. but when i try to use RestSharp with this code:
RestSharp.RestRequest request = new RestSharp.RestRequest("/resource");
request.AddParameter("par1", val, RestSharp.ParameterType.RequestBody);
request.AddParameter("par2", val, RestSharp.ParameterType.RequestBody);
request.AddHeader("Origin", "http://someurl.com");
request.Method = RestSharp.Method.POST;
RestSharp.RestClient client = new RestSharp.RestClient("http://someurl.com");
var response = client.Execute(request);
then fiddler show me the request sent by GET method instead of POST?
I check another time my fiddler and found this issue:
Content-Type: par1
why this is happening for me?
Change your ParameterType argument to GetOrPost and it will work
request.AddParameter("par1", val, RestSharp.ParameterType.GetOrPost);
request.AddParameter("par2", val, RestSharp.ParameterType.GetOrPost);
Initialize Request as POST with JSON.
var client = new RestClient(PreUri);
var request = new RestRequest(Uri, Method.POST) {RequestFormat = DataFormat.Json};
Add object in body
request.AddBody(obj);
Execute
var cancellationTokenSource = new CancellationTokenSource();
var response = await client.ExecuteTaskAsync(request, cancellationTokenSource.Token);
I was stupidly doing mistake to call "client.Get" instead of "client.Post". May be this post helps other.
var client = new RestClient("https://someservice.com");
var request = new RestRequest("/token/", Method.POST, DataFormat.Json).AddJsonBody(SomeObject);
var response = client.Get(request);
I was expecting this code to make POST request. Because i specified it as Method.POST.
But after a few hours, i saw my mistake. Yeas i was specifying the method. But just after i am calling client.Get(request); This changes the metod to GET.
So, the right way to use POST request is like follows:
var client = new RestClient("https://someservice.com");
var request = new RestRequest("/token/", DataFormat.Json).AddJsonBody(SomeObject);
var response = client.Post(request);
I'm having a little trouble posting form submissions from C# to a KOBO Server (https://kf.kobotoolbox.org). The response I get is 'Bad Gateway'.
Here's my code:
var client = new RestClient("https://kc.kobotoolbox.org/api/v1/submissions");
//var client = new RestClient("https://kc.kobotoolbox.org/api/v1/forms/{pk}/labels");
client.Authenticator = new HttpBasicAuthenticator("a_user", "alpha9876");
//client.AddDefaultUrlSegment("pk", "31037");
//client.AddDefaultUrlSegment("tags", "tag1, tag2");
// client.AddDefaultUrlSegment("format", "xls");
//client.AddDefaultUrlSegment("url", "https://kc.kobotoolbox.org/api/v1/projects/1");
//client.AddDefaultUrlSegment("owner", "https://kc.kobotoolbox.org/api/v1/users/ona");
//client.AddDefaultUrlSegment("name", "project 1");
//client.AddDefaultUrlSegment("date_created", "2013-07-24T13:37:39Z");
//client.AddDefaultUrlSegment("date_modified", "2013-07-24T13:37:39Z");
var request = new RestRequest(Method.POST);
IRestResponse response = client.Execute(request);
request.AddHeader("header", "xml");
request.Resource = "C:\\Users\\Susan\\Desktop\\xmltest\\form_linkage_parentform.xml";
Could anyone help with a sample snippet of what the C# code for making this POST HTTP request would probably look like? Based on this: https://kc.kobotoolbox.org/api/v1/
Thank you!
I finally managed to do it using CSV files (https://kc.kobotoolbox.org/api/v1/forms) as follows:
var client = new RestClient("https://kc.kobotoolbox.org/api/v1/forms/{pk}/csv_import");
client.Authenticator = new HttpBasicAuthenticator("user_name", "password");
client.AddDefaultUrlSegment("pk", "31045");
string file_path = Server.MapPath("~/myform.csv");
var request = new RestRequest(Method.POST);
request.AddFile("csv_file", file_path);
IRestResponse response = client.Execute(request);