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.
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);
Basically, I've been trying to authenticate through oauth2 on c# using restsharp, but I am receiving a bad request response, I'm not sure if it's something related to the API configuration or if it's something I'm missing In my code.
public string getToken(string email, string password)
{
var restclient = new RestClient(loginUrl);
RestRequest request = new RestRequest("request/oauth") { Method = Method.GET };
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("email", HttpUtility.UrlPathEncode(email));
request.AddParameter("password", HttpUtility.UrlPathEncode(password));
request.AddParameter("grant_type", HttpUtility.UrlPathEncode("password"));
var tResponse = restclient.Execute(request);
var responseJson = tResponse.Content;
string token = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseJson)["access_token"].ToString();
return token;
}
this is the response when I execute that code
An this is the postman execution
Thanks!
I think there problem with adding parameters the way you are adding.
latest restsharp support this,
Also,avoid encoding of params by setting to false
var request = new RestRequest("resource", Method.GET);
request.AddQueryParameter("email", "test#test.com",false);
var restclient = new RestClient(loginUrl); I think you need to check your url.
Try this.. you OAuth is password grantype are your sure your not missing any credentials like client_id, scope and client_secret.
public static string getAccessToken(string usern, string pswd)
{
RestClient client = new RestClient(ConfigurationManager.AppSettings["TokenUrl"]);
RestRequest request = new RestRequest() { Method = Method.GET};
request.AddParameter("grant_type", "password", ParameterType.GetOrPost);
request.AddParameter("username", usern, ParameterType.GetOrPost);
request.AddParameter("password", pswd, ParameterType.GetOrPost);
IRestResponse response = client.Execute(request);
var responseJson = response.Content;
var token = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseJson)["access_token"].ToString();
return token;
}
I have a paid subscription to Seeking Alpha and have a cookkie which enables me to get full data from https://seekingalpha.com/symbol/AAPL/financials-data?period_type=quarterly&statement_type=income-statement&order_type=latest_left&is_pro=True
I'd like to collect JSON response using C#
Below is my horrible code
string cookie = "my super secret cookie string";
var request = new RestRequest(Method.GET);
request.AddHeader("content-type", "application/json");
request.AddHeader("Accept", "*/*");
request.AddHeader("User-Agent","Mozilla/5.0");
request.AddHeader("X-Requested-With", "XMLHttpRequest");
string url = "https://seekingalpha.com/symbol/AAPL/financials-data?period_type=quarterly&statement_type=income-statement&order_type=latest_left&is_pro=True";
request.AddParameter("cookie", cookie, ParameterType.Cookie);
var client = new RestClient(url);
var queryResult = client.Execute(request);
Console.WriteLine(queryResult.Content);
How can I get it to return JSON to me? I am getting something but not the JSON I want
Try updating your Access header to application/json.
request.AddHeader("Accept", "application/json");
Accept indicates what kind of response from the server the client can accept.
You can get more info for Accept from Header parameters: “Accept” and “Content-type” in a REST context
After poking around for a bit I figured it out. For the benefit of all:
private bool FinancialStatement(string symbol, string statement, string period)
{
var target = $"{BASE_URL}{symbol}/financials-data?period_type={period}&statement_type={statement}&order_type=latest_left&is_pro=True";
var client = new RestClient(target);
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Cookie", MACHINE_COOKIE);
IRestResponse response = client.Execute(request);
dynamic responseObj;
try
{
responseObj = JsonConvert.DeserializeObject(response.Content);
}
catch (Exception)
{
return false;
}
return response.IsSuccessful;
}
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);
Using C#, .Net 4,5, RestSharp v4.0.3
Attempting to create an api_key in GoCardless
I create a RestClient like this:
var client = new RestClient();
client.BaseUrl = SandboxBaseUrl;
client.Authenticator = new HttpBasicAuthenticator(apiKeyId, apiKey);
client.AddDefaultHeader("GoCardless-Version", Properties.Settings.Default.GoCardlessVersion);
client.AddDefaultHeader("Accept", "application/json");
client.AddDefaultHeader("content-type", "application/json");
request.AddHeader("content-type", "application/json");
When I post to GoCardless I get the error
{"error":{"message":"'Content-Type' header must be application/json or application/vnd.api+json ......
After a lot of fruitless searching I gave up and used the solutions in older StackOverflow postings. Such as
// Create the Json for the new object
StringBuilder requestJson = new StringBuilder();
var requestObject = new { api_keys = new { name = name, links = new { role = role } } };
(new JavaScriptSerializer()).Serialize(requestObject, requestJson);
...
// Set up the RestSharp request
request.Parameters.Clear();
request.AddParameter("application/json", requestJson, ParameterType.RequestBody);
I can see why this works - and even perhaps the intention of RestSharp doing it this way.