Trouble with POST/PUT using RestSharp - c#

The first listing below is using RestSharp library. The second one uses the Hammock REST API library. They are very similar. The Hammock one works, the RestSharp one does not. The 'config' object is a DTO object. The RestSharp version does not even send a message, but also does not throw an exception. Does not make a difference whether I set the Method to PUT or POST, the behavior is the same.
What on earth am I doing wrong?
##
var client = new RestClient() { BaseUrl = "http://server/AgentProxy", };
var request = new RestRequest() { Resource = "/AgentConfiguration", Method = Method.POST, RequestFormat = DataFormat.Json };
request.DateFormat = DateFormat.Iso8601;
request.AddHeader("content-type", "application/json; charset=utf-8");
request.AddBody(config);
client.Execute(request);
##
##
var client = new Hammock.RestClient() { Authority = "http://server/AgentProxy" };
var request = new Hammock.RestRequest() { Path = "/AgentConfiguration", Method = Hammock.Web.WebMethod.Post, Timeout = new TimeSpan(0, 0, 5), Credentials = null };
request.AddHeader("content-type", "application/json; charset=utf-8");
request.AddPostContent(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(config, new IsoDateTimeConverter())));
client.Request(request);
##
The two libraries seem more similar than different. Both use Newtonsoft Json library.
Thank you for your time,
Jim

Related

RestSharp api hook never gets called

I am using restsharp to call the zoom api but the api hook never gets executed. Here is what The tokenString(JWT) is correct when logging it out. No logs appear on zoom.
I have tested through postman with the same paramaters and it works fine. Nothing comes back in my restresponse, it is like it isn't even being called. I am calling this from within an asmx web method
Here is what I have:
var client = new RestClient("https://api.zoom.us");
var request = new RestRequest("/v2/users/myemail#mycompany.com/meetings", Method.POST)
{
RequestFormat = DataFormat.Json
};
request.AddJsonBody(new { topic = "Meeting with test", duration = "10", start_time = "2021-08-20T05:00:00", type = "2" });
request.AddHeader("authorization", String.Format("Bearer {0}", tokenString));
request.AddHeader("content-type","application/json");
IRestResponse restresponse = client.Execute(request);
The issues was with TLS. Posting the following before my call solved it:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

C# Send data with method POST to API

Dont know what i doing wrong, need to fill database with datas from my VSTO Outlook Addin.
jObjectbody.Add( new { mail_from = FromEmailAddress }); mail_from is name of column in database, FromEmailAddress is value from my Outlook Addin
How to send to API https://my.address.com/insertData correctly ?
RestClient restClient = new RestClient("https://my.address.com/");
JObject jObjectbody = new JObject();
jObjectbody.Add( new { mail_from = FromEmailAddress });
RestRequest restRequest = new RestRequest("insertData", Method.POST);
restRequest.RequestFormat = DataFormat.Json;
restRequest.AddParameter("text/html", jObjectbody, ParameterType.RequestBody);
IRestResponse restResponse = restClient.Execute(restRequest);
error : Could not determine JSON object type for type <>f__AnonymousType0`1[System.String].
If i try this in Postman (POST->Body->raw->JSON) data are strored in database, except dont use value just data.
{
"mail_from":"email#email.com"
}
thanks for any clue achieve success
You can use restRequest.AddJsonBody(jObjectbody); instead of AddParameter (which I believe adds a query string).
See the RestSharp AddJsonBody docs. They also mention to not use some sort of JObject as it wont work, so you will probably need to update your type as well.
The below might work for you:
RestClient restClient = new RestClient("https://my.address.com/");
var body = new { mail_from = "email#me.com" };
RestRequest restRequest = new RestRequest("insertData", Method.POST);
restRequest.AddJsonBody(body);
IRestResponse restResponse = restClient.Execute(restRequest);
// extra points for calling async overload instead
//var asyncResponse = await restClient.ExecuteTaskAsync(restRequest);

C# Oracle Rest API, Authentication Issue

I am trying to use Ocacle's Financial REST API and I'm having trouble making it work in C# in VS2019.
I can confirm the restful call works using Postman, so I know my credentials are fine but I must be missing something trying this with in code.
So URL is like so:
http://MYCLOUDDOMAIN/fscmRestApi/resources/11.13.18.05/ledgerBalances?finder=AccountBalanceFinder;accountCombination=3312-155100-0000-0000-0000-00000,accountingPeriod=Feb-20,currency=USD,ledgerSetName=Ledger,mode=Detail&fields=LedgerName,PeriodName,Currency,DetailAccountCombination,Scenario,BeginningBalance,PeriodActivity,EndingBalance,AmountType,CurrencyType,ErrorDetail
So I stick that in postman, put in my credentials (basic auth) and it works find. In VS I've tried both the RestSharp way and basic HTTPRequest way as follows:
HttpWebRequest r = (HttpWebRequest)WebRequest.Create("/fscmRestApi/resources/11.13.18.05/ledgerBalances?finder=AccountBalanceFinder;accountCombination=3312-155100-0000-0000-0000-00000,accountingPeriod=Feb-20,currency=USD,ledgerSetName=Ledger US,mode=Detail&fields=LedgerName,PeriodName,Currency,DetailAccountCombination,Scenario,BeginningBalance,PeriodActivity,EndingBalance,AmountType,CurrencyType,ErrorDetail");
r.Method = "GET";
string auth = System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("Username" + ":" + "Password"));
r.Headers.Add("Authorization", "Basic" + " " + auth);
r.ContentType = "application/vnd.oracle.adf.resourcecollection+json";
using (HttpWebResponse resp = (HttpWebResponse)r.GetResponse())
{
int b = 0;
}
RestSharp:
var client = new RestClient("http://MYCLOUDDOMAIN/fscmRestApi/resources/11.13.18.05/ledgerBalances?finder=AccountBalanceFinder;accountCombination=3312-155100-0000-0000-0000-00000,accountingPeriod=Feb-20,currency=USD,ledgerSetName=Ledger US,mode=Detail&fields=LedgerName,PeriodName,Currency,DetailAccountCombination,Scenario,BeginningBalance,PeriodActivity,EndingBalance,AmountType,CurrencyType,ErrorDetail");
client.Authenticator = new RestSharp.Authenticators.HttpBasicAuthenticator("UserName", "Password");
//Tried authorization this way as well.
//JObject AuthRequest = new JObject();
//AuthRequest.Add("Username", "UserName");
//AuthRequest.Add("Password", "Password");
var request = new RestRequest();
request.Method = Method.GET;
request.RequestFormat = DataFormat.Json;
//request.AddParameter("text/json", AuthRequest.ToString(), ParameterType.RequestBody);
request.AddHeader("Content-Type", "application/vnd.oracle.adf.resourcecollection+json");
request.AddHeader("REST-Framework-Version", "1");
var response = client.Get(request);
No matter what I try I am always 401 not authorized. I suspect its some kind of header thing? I can't see the raw request header in postman
I am new to REST. I am used to using WSDLs soap services.
Try this.
var handler = new HttpClientHandler
{
Credentials = new NetworkCredential("username", "password")
};
using (var client = new HttpClient(handler))
{
var result = await client.GetAsync("url");
}
Good luck!
I figured out what the problem was.
In postman, it was fine with the URL I posted being HTTP but in C# code it was not. I switched the URL to HTTPS and it started working just fine.

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

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