RestSharp api hook never gets called - c#

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;

Related

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.

Restsharp returns 403 while Postman returns 200

This is the (modified) snippet that Postman gives for successful call to my page.
var client = new RestClient("http://sub.example.com/wp-json/wp/v2/users/me");
var request = new RestRequest(Method.GET);
request.AddHeader("authorization", "Basic anVyYTp3MmZacmo2eGtBOHJsRWrt");
IRestResponse response = client.Execute(request);
But when placed in my c# app it returns 403 forbidden, while Postman makes it and recieves 200.
The same thing happens when I use httpclient in my app (403).
Use RestClient.Authenticator instead:
var client = new RestClient("http://sub.example.com/wp-json/wp/v2/users/me")
{
Authenticator = new HttpBasicAuthenticator("User", "Pass")
};
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
Edit:
Since the issue (as mentioned in the comments) is the fact that RestSharp doesn't flow the authentication through redirects, I'd suggest going with a combination of HttpClient with a HttpClientHandler where you set the authentication to flow.
[Solution]
Use the below line for the header
Headers.Add("User-Agent: Other");

Update event with outlook rest api fails with Method Not Allowed

I have an application that uses the outlook REST API for creating events on the user's calendar. The creation of the event works perfectly, but once I tried to to exactly as this post indicates, I get 405 Method Not Allowed.
the error details are as follow:
{"error":{"code":"ErrorInvalidRequest","message":"The OData request is not supported."}}
here's a part of my code:
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, new Uri("https://outlook.office365.com/api/v1.0/me/events/"+meeting.OutlookEventId));
var auth = "Bearer " + token;
request.Headers.Add("Accept", "application/json");
request.Headers.Add("Authorization", auth);
var converters = new List<JsonConverter>();
converters.Add(new MyStringEnumConverter());
var createResponse = #"{
'Location': {
'DisplayName': 'Your office'
}
}";
request.Content = new StringContent(createResponse);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await client.SendAsync(request);
I have the user token sotred on the "token" variable, as well as the outlook event Id on the "meeting.OutlookEventId" variable.
Any ideas?
Thank you very much!
I feel like a total fool...
I was sending a POST when this request required a PATCH
I just replaced
HttpMethod.Post
for
new HttpMethod("PATCH")

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();

Trouble with POST/PUT using RestSharp

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

Categories