my webservice restful client fail post c# bearer - c#

I Write one application to access one Webservice Restful using C#, i get the Token with success, i access other services without parameters fine, but when i need to send parameters in POST method it´s not work.
In other side, the Wesbservice dont see my post.
Can someone help-me about this ?
Here is my code.
string urlMethod = metodo;
// "/api/v1/organizacao/criar";
var accessToken = IntegraPb.GetToken();
var client = new RestClient(Sincronizador.Properties.Settings.Default.apiUrl);
var request = new RestRequest(urlMethod, Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Authorization", "Bearer " + accessToken);
var jsserie = new System.Web.Script.Serialization.JavaScriptSerializer();
// obj is my class to serialize
request.AddJsonBody(jsserie.Serialize(obj));
IRestResponse response = client.Execute(request);
This image is the request object

AddJsonBody receives a object, not a serialized string of your object. It does the serialization internally.
So use this instead:
request.AddJsonBody(obj);

Related

Restsharp Request gives "Argument 1: cannot convert from 'RestSharp.Method' to 'string?'" error

I am trying to call POST API request using restSharp 108.0.1v.
The code is as below;
var client = new RestClient("https://driver-vehicle-licensing.api.gov.uk/vehicle-enquiry/v1/vehicles");
var request = new RestRequest(Method.Post);
request.AddHeader("x-api-key", "MYAPIKEY");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n\t\"registrationNumber\":\"AA19AAA\"\n}", ParameterType.RequestBody);
RestResponse response = client.Execute(request);
The snippet Method.Post of var request = new RestRequest(Method.Post);gives the error that I mentioned.
Please help me to solve this issue ?
Looking at the documentation here the first parameter of the RestRequest constructor is the subpath to the resource you want to access. Instead you should do something like the following
var client = new RestClient("https://driver-vehicle-licensing.api.gov.uk");
var request = new RestRequest("vehicle-enquiry/v1/vehicles", Method.Post);
// ... or I believe this should work as well:
var client = new RestClient("https://driver-vehicle-licensing.api.gov.uk/vehicle-enquiry/v1");
var request = new RestRequest("vehicles", Method.Post);

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?

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).

Cannot PUT/POST using Rest Sharp using XML

I want to create/modify an issue on redmine using the PUT/POST methods of restSharp.
I cannot find valuable information about xml PUT/POST using Rest sharp. I tried various methods from restsharp.org like Addbody("test", "subject"); , IRestResponse response = client.Execute(request); but there is no change in Redmine. What am I doing wrong?
POST gives a "Only get, put, and delete requests are allowed." message.
PUT gives a "Only get, post, and delete requests are allowed." message.
My Code
RestClient client = new RestClient(_baseUrl);
client.Authenticator = new HttpBasicAuthenticator(_user, _password);
RestRequest request = new RestRequest("issues/{id}.xml", Method.POST);
request.AddParameter("subject", "Testint POST");
request.AddUrlSegment("id", "5");
var response = client.Execute(request);
The problem was in the serialization. My Issue class contains object of various other classes which was causing a problem in the serialization.
This is how we did it:
RestRequest request = new RestRequest("issues/{id}.xml", Method.PUT);
request.AddParameter("id", ticket.id, ParameterType.UrlSegment);
request.XmlSerializer = new RedmineXmlSerializer();
request.AddBody(ticket);
RestClient client = new RestClient(_baseUrl);
client.Authenticator = new HttpBasicAuthenticator(_user, _password);
IRestResponse response = client.Execute(request);
Your code looks ok to me, I'm unsure if you need this but we added this header when using RestSharp for json against a WebAPI host:
request.AddHeader("Accept", "application/xml");

GoToWebinar - Request not in expected format - RestSharp

Similar to this forum post:
https://developer.citrixonline.com/forum/request-not-expected-format
However he didn't really explain what he found was wrong with his code.
I'm using RestSharp to make API calls. I've been able to get it to work great to pull an list of upcoming webinars however when I try to register participant I keep getting a 400/Request not in expected format error.
Following this documentation https://developer.citrixonline.com/api/gotowebinar-rest-api/apimethod/create-registrant, here is my code:
var client = new RestClient(string.Format("https://api.citrixonline.com/G2W/rest/organizers/{0}/webinars/{1}/registrants", "300000000000xxxxxx", btn.CommandArgument));
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Accept", "application/json");
request.AddHeader("Accept", "application/vnd.citrix.g2wapi-v1.1+json");
request.AddHeader("Authorization", "OAuth oauth_token=" + System.Configuration.ConfigurationManager.AppSettings["GoToWebinar"]);
request.AddParameter("firstName", LoggedInUser.FirstName);
request.AddParameter("lastName", LoggedInUser.LastName);
request.AddParameter("email", LoggedInUser.Email);
var response = client.Execute(request);
var statusCode = response.StatusCode;
Any insights on how I can figure out why I keep getting that error?
Thank you!
Instead of using AddParamter (which adds key/value parameters to the request body), you need to write JSON instead:
request.DataFormat = DataFormat.Json;
request.AddBody(new {
firstName = LoggedInUser.FirstName,
lastName = LoggedInUser.LastName,
email = LoggedInUser.Email
});
You'll also need to clear the handlers (which automatically set the Accept header) if you want to specify them directly:
client.ClearHandlers();

Categories