RestSharp PUT request parameters - c#

I'm having issues figuring out how to create a put request using RestSharp.
I need to pass an integer followed by a JSON body in the same request.
So far I have this:
for (var i = 0; i < ReorderedTasks.Count; i++) {
var reorderedTasksJson = new JavaScriptSerializer().Serialize(ReorderedTasks[i]);
var request = new RestRequest("api/task/5/{ID}/", Method.PUT);
request.AddParameter("ID", ReorderedTasks[i].ID.ToString(), ParameterType.UrlSegment);
request.AddParameter("application/json; charset=utf-8", reorderedTasksJson, ParameterType.RequestBody);
client.Execute(request);
}
I've tested out the JSON ad requestBody on POST and it works fine. I think my issue is with the first parameter I'm trying to pass ReorderedTasks[i].ID , I'm not sure if I'm handling the passing of this correctly.
I've initialised client at the beginning of my class.
Problem is the DB isn't updating and I need to isolate the problem. Is the above the correct way in dealing with my two parameters needing passed?

I suggest to put ReorderedTasks[i].ID.ToString() directly to url path.
var request = new RestRequest($"api/task/5/{ReorderedTasks[i].ID.ToString()}/", Method.PUT);
It will help to reduce possible problems with http request format.

I'll add it here, so someone will benefit from it.
If your endpoint URL have parameters like ?param=value&param2=value that you want to pass along with request RestSharp's AddParameter(string, string) won't work with PUT method (but it works just fine with GET or if endpoint doesn't have URL parameters, so it is deceiving)
Use AddParameter(string, string, ParameterType.QueryString) in order to PUT Method work correctly.

Well it depends on what does the webApi expect..
You could use Fiddler to inspect what being sent through the wire and what response You are getting (http://www.telerik.com/fiddler)
Also - here are some sample's how other users use RestSharp
How do I use PUT in RestSharp?

Related

httpClient.PostAsync() performs GET request anyway

I really am not sure what is happening.
I'm using an HttpClient to post XML content to a remote server using the PostAsync method like this:
using var content = new StringContent(payload, Encoding.UTF8, "application/xml");
using var response = await _httpClient.PostAsync(string.Empty, content);
... where payload is a string, and relative uri is empty because I just need to call base uri of httpclient.
I can perform same request in Postman and it works fine.
The issue is, for some reason httpclient actually performs a GET request instead of POST, and ignores content whatsoever:
I've checked in Postman, and it seems like it is a normal response from the server to GET request.
I've also tried
using var response = await _httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Post, string.Empty){Content = content});
... and it gives the same result.
This looks like a very weird issue to me, as I've never seen http client behaving like this in the past. Could anyone please explain why is this happening? Thanks!
OK, so the issue was actually with server.
It redirected all the requests with URLs not ending with "/", like http://address.com/page to the same address but ending with "/" - http://address.com/page/, and lost the method and content in process.
As #Jimi mentioned, the RequestMessage field in HttpResponseMessage contains the info about the last request that reached the server, therefore initial request data was lost, and I mistook it for HttpClient making wrong requests.

How can I send a GET request with json body?

Is there any way at all that I can send a GET request with a JSON body using c#? I am making a call to an API to retrieve a list of items using a GET request, but I have to pass the customer_id in JSON. I am able to do this successfully in Postman and Python. However, the legacy app that I am working with is built as c# .NET winform. I am able to make other calls using HttpClient, but after some research I am finding that this class does not allow GET request with body except when using CORE. Are there any other alternatives?
According to Ian Kemp's answer to this question,
This can be done in .NET Framework projects using the System.Net.Http.WinHttpHandler Library. (I'll just add the relevant part of the answer here, but I recommend to go check his full answer)
First, Install the System.Net.Http.WinHttpHandler Library from Nuget and then use it as your http client handler as described below:
var handler = new WinHttpHandler();
var client = new HttpClient(handler);
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("some url"),
Content = new StringContent("some json", Encoding.UTF8, ContentType.Json),
};
var response = await client.SendAsync(request).ConfigureAwait(false);
//Handle the response as you see fit
With the HTTP method GET, the body has no meaning. It will be ignored according to the HTTP specs. When getting resources from your API using the GET http verb, you have the option to pass a query string (http://somedomain.com/api/getValues?key=1) or pass the parameter directly in the url (http://somedomain.com/api/getValues/1)
To receive it in your controller, you would have to expect either the parameter or the query string like this:
If the parameter is in the URL:
[HttpGet("/api/getValues/{id}")]
public async Task<IActionResult> GetValues(int id){}
(Make sure that your parameter name in the function matches the name that you gave to it in the route)
If the parameter is a query string:
[HttpGet("/api/getValues")]
public async Task<IActionResult> GetValues(string key){}
(Make sure that the query string key name matches the parameter name in your function)
The best practice is to use the parameter in the URL. Query strings are very useful, but you have to know when to use it, for example, if you want to narrow down the results given certain values, you could the query string to send them.

Put call works in PostMan but not in RestSharp: Getting a bad request

I want to call an endpoint with a Put command.
In Postman
I can put example https://example.com/customers/106. I then add a body of type application/json (under raw).
When I Put this body to the endpoint, I get a 200 OK.
The endpoint I use requires two custom headers and a content-type, which I have made under headers. So I add three headers: X-AppSecretToken, X-AgreementGrantToken and the Content-Type (to application/json).
In RestSharp
Here I use the following. The putstr is the exact same body I Put as I do in Postman:
var restclient = new RestSharp.RestClient("https://example.com");
var request = new RestRequest("/customers/" + customerId, Method.PUT);
request.AddHeader("X-AppSecretToken", systemToken);
request.AddHeader("X-AgreementGrantToken", userToken);
request.AddHeader("Accept", "application/json");
request.AddJsonBody(putstr);
var response = restclient.Execute(request);
Now, when I do this, I get the following response which is a custom error from the API I am calling:
"{\"message\":\"Error converting value SOME STUFF}}\\\" to type 'eco.rest.Models.Customer'. Path '', line 1, position 605.\",\"errorCode\":\"E00500\",\"developerHint\":\"The JSON payload could not be parsed. The error message should give you a good indication of where the error is located. One common reason for this error is a missing '{' or a '}' in your payload.\",\"logId\":\"123fc6fb4964a141f612ae8ae7571446\",\"httpStatusCode\":400,\"logTime\":\"2018-05-20T21:56:56\"}"
How to fix?
Normally, I'd never ask this question. If someone else asked, I would say: open Fiddler or a similar tool and see how requests are different.
I have some troubles with this, because it's HTTPS.
When I debug through my code, I simply don't see the call inside Fiddler. I also installed Charles, but also no luck. Not sure what the problem is.
However, I thought that someone who reads this can probably come up with the problem. My own assumptions are I maybe have added the headers in a wrong way, the JSON body is encoded different or similar - but I am really unsure how to move on. I hope someone can help!
Your putstr value seems to be a JSON value.
AddJsonBody will convert this JSON value into another JSON value.
You should use the original object instead of putstr.

WebRequest: Query string data vs x-www-form-urlencoded content

I am trying to call Google's OAuth2 authentication service as per these instructions: https://developers.google.com/accounts/docs/OAuth2ForDevices
I put all of the required parameters into the query string and sent the request. This worked for the "Obtaining a user code" section but not for the "Obtaining Access and Refresh Tokens" section.
After much playing around and getting 400 Bad Request errors, I found that, instead of putting the data in the query string, you can create a request with a FormUrlEncodedContent and send the data through as content with application\x-www-form-urlencoded Content-Type.
Here is the code before:
var requestMessage = new HttpRequestMessage();
requestMessage.Method = "POST";
requestMessage.RequestUri = new Uri(fullUrl);
Where fullUrl is something like:
https://accounts.google.com/o/oauth2/device/code?client_id=812741506391-h38jh0j4fv0ce1krdkiq0hfvt6n5amrf.apps.googleusercontent.com&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile
And the new code is:
var requestMessage = new HttpRequestMessage();
requestMessage.Method = "POST";
requestMessage.RequestUri = new Uri(url);
requestMessage.Content = new FormUrlEncodedContent(CreateDictionary(queryStringNames, queryStringValues));
Where url is:
https://accounts.google.com/o/oauth2/device/code
and queryStringNames and queryStringValues are string arrays of the names and values of the required parameters.
What is the difference between these two methods? Is it safe to assume that all POST calls can use the URL Encoded Content requests instead of putting the data in the query string?
In general, POST requests do not need query string but it is still subjected to Server's logic implementation. In case of OAuth which is quite known standard and they do follow good practice, it is safe to use form encoded data unless mentioned explicitly in API to send Parameter as query string.
Query String & Post data are two different set of parameters. If server is expecting Query string then you must send query string only. It all depends on how server side logic is implemented. You can not use them alternatively. Most API documentation specify clearly what are they expecting.

How to access the HTTP request body using RestSharp?

I'm building a RESTful API client using C# .NET 3.5.
I first started building it with the good old HttpWebClient (and HttpWebResponse), I could do whatever I wanted with. I were happy. The only thing I stumbled upon was the automatic deserialization from JSON response.
So, I've heard about a wonderful library called RestSharp (104.1) which eases the development of RESTful API clients, and automatically deserialize JSON and XML responses. I switched all my code on it, but now I realize I can't do things I could do with HttpWebClient and HttpWebResponse, like access and edit the raw request body.
Anyone has a solution?
Edit: I know how to set the request body (with request.AddBody()), my problem is that I want to get this request body string, edit it, and re-set it in the request (in other words: updating the request body on the fly)
The request body is a type of parameter. To add one, you can do one of these...
req.AddBody(body);
req.AddBody(body, xmlNamespace);
req.AddParameter("text/xml", body, ParameterType.RequestBody);
req.AddParameter("application/json", body, ParameterType.RequestBody);
To retrieve the body parameter you can look for items in the req.Parameters collection where the Type is equal to ParameterType.RequestBody.
See code for the RestRequest class here.
Here is what the RestSharp docs on ParameterType.RequestBody has to say:
If this parameter is set, it’s value will be sent as the body of the
request. The name of the Parameter is ignored, and so are additional
RequestBody Parameters – only 1 is accepted.
RequestBody only works on POST or PUT Requests, as only they actually
send a body.
If you have GetOrPost parameters as well, they will overwrite the
RequestBody – RestSharp will not combine them but it will instead
throw the RequestBody parameter away.
For reading/updating the body parameter on-the-fly, you can try:
var body = req.Parameters.FirstOrDefault(p => p.Type == ParameterType.RequestBody);
if (body != null)
{
Console.WriteLine("CurrentBody={0}", body.Value);
body.Value = "NewBodyValue";
}
Or failing that, create a new copy of the RestRequest object with a different body.

Categories

Resources