Converting HttpClient to RestSharp - c#

I have Httpclient functions that I am trying to convert to RestSharp but I am facing a problem I can't solve with using google.
client.BaseAddress = new Uri("http://place.holder.nl/");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",access_token);
HttpResponseMessage response = await client.GetAsync("api/personeel/myID");
string resultJson = response.Content.ReadAsStringAsync().Result;
This Code is in my HttpClient code, which works good, but I can't get it to work in RestSharp, I always get Unauthorized when using RestSharp like this:
RestClient client = new RestClient("http://place.holder.nl");
RestRequest request = new RestRequest();
client.Authenticator = new HttpBasicAuthenticator("Bearer", access_token);
request.AddHeader("Accept", "application/json");
request.Resource = "api/personeel/myID";
request.RequestFormat = DataFormat.Json;
var response = client.Execute(request);
Am I missing something with authenticating?

This has fixed my problem:
RestClient client = new RestClient("http://place.holder.nl");
RestRequest request = new RestRequest("api/personeel/myID", Method.GET);
request.AddParameter("Authorization",
string.Format("Bearer " + access_token),
ParameterType.HttpHeader);
var response = client.Execute(request);
Upon sniffing with Fiddler, i came to the conclusion that RestSharp sends the access_token as Basic, so with a plain Parameter instead of a HttpBasicAuthenticator i could force the token with a Bearer prefix

Try this
RestClient client = new RestClient("http://place.holder.nl");
RestRequest request = new RestRequest("api/personeel/myID",Method.Get);
request.AddParameter("Authorization",$"Bearer {access_token}",ParameterType.HttpHeader);
request.AddHeader("Accept", "application/json");
request.RequestFormat = DataFormat.Json;
var response = client.Execute(request);

If anyone happens on this, it looks like as of V 106.6.10 you can simply add default parameters to the client to save yourself from having to add your Auth token to every request method:
private void InitializeClient()
{
_client = new RestClient(BASE_URL);
_client.DefaultParameters.Add(new Parameter("Authorization",
string.Format("Bearer " + TOKEN),
ParameterType.HttpHeader));
}

Related

Sending a PUT request to the ZENDESK API to update an organisation via c#

I'm getting a 422 error when sending the http rerquest to the zendesk API to update an organisation. The JSON I am sending is valid so not sure where the issue is. I am using the C# http client.
The code:
string host = "https://MYZENDESK.zendesk.com";
var file = "/api/v2/organizations/" + connectDetails.ToString() + ".json";
var details = this.richTextBox1.Text.Replace(#"\",#"\\");
var json = "{\"organization\": {\"details\" :\"" + details + "\"}}";
Console.Write(json);
Console.Read();
var jobject = JsonConvert.DeserializeObject<JObject>(json);
using (var client = new HttpClient())
{
System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
client.DefaultRequestHeaders.Add("authorization", "Basic xxxxxxxxx");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//var response = client.GetAsync(host + file).Result;
var response = client.PutAsync(host + file, new StringContent(json, Encoding.UTF8, "application/json")).Result;
if (!response.IsSuccessStatusCode)
throw new Exception(response.ReasonPhrase);
}
}
I was hopeing this would work. I can update via postman just fine with the same configuration but there must be some issue with my code.
Found a solution using RestSharp. Had tried this previously but have found that an older version of RestSharp is needed:
using RestSharp;
//use RestSharp v106.1
static void APIcall() {
var client = new RestClient("https://xxxxx.zendesk.com/api/v2/organizations/xxxxx");
client.Timeout = -1;
var request = new RestRequest(Method.PUT);
request.AddHeader("content", "application/json");
request.AddHeader("Authorization", "Basic xxxxx");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Cookie", "_zendesk_cookie=xxxxxx");
var body = xxxxx
request.AddParameter("application/json", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Console.ReadLine();
}
APIcall();

WebException: The request was aborted: Could not create SSL/TLS secure channel but working with POSTMAN

I am calling Power school API to fetch student data. Using the below code.
public Token GetAuthToken(string baseUrl, string authKey)
{
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;
var client = new HttpClient();
client.BaseAddress = new Uri(_url);
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var values = new Dictionary<string, string> { { "grant_type", "client_credentials" } };
var content = new FormUrlEncodedContent(values);
client.DefaultRequestHeaders.Add("Authorization", $"Basic {authKey}");
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
Content = content,
};
request.Headers.Add("Authorization", $"Basic {authKey}");
var response = client.PostAsync(baseUrl+ "/oauth/access_token", content).Result;
var responseString = response.Content.ReadAsStringAsync().Result;
var token = JsonConvert.DeserializeObject<Token>(responseString);
return token;
}
catch (Exception e)
{
throw;
}
finally
{
}
}
This code was working fine 3 months ago but now started giving error WebException: The request was aborted: Could not create SSL/TLS secure channel.
I tried to post the same request from POSTMAN and it was able to connect and get data. Postman shows TLS 1.2. See the below Image
I also tried the code generated from the POSTMAN and it was giving the same error. Below is the code generated from POSTMAN
var client = new RestClient("<MY URL HERE>");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic <MY KEY HERE>");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "client_credentials");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
I am using these on Windows Server 2012 R2. POSTMAN is able to connect while C# (.Net Framework 4.8) is failing.
What could be the issue? I tried a combination of all TLS versions available from TLS to TLS13
EDIT
When I check event logs, I am getting below error

Get OAuth2.0 Bearer Token from AuthURL and ClientID

In Postman I am able to generate the Bearer token using
Callback URL
Auth URL
Client ID
How do I do the same using C# code?
This is the code I am running but the response body does not have the bearer token.
var client = new RestClient("AuthURL");
var requestToken = new RestRequest(Method.POST);
requestToken.AddHeader("cache-control", "no-cache");
requestToken.AddHeader("content-type", "application/x-www-form-urlencoded");
requestToken.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=123", ParameterType.RequestBody);
IRestResponse response = client.Execute(requestToken);
string res = response.Content;
where is your username and password?
var client = new RestClient("http://example.com");
client.Authenticator = new HttpBasicAuthenticator(userName, password);
var request = new RestRequest("resource", Method.GET);
client.Execute(request);
might be a duplicate of this question
RestSharp HttpBasicAuthentication - example

RestSharp body always empty

I need to call a Post service with RestSharp
var client = new RestClient(url);
var request = new RestRequest(url,Method.POST);
request.AddHeader("Content-type", "application/json");
request.AddJsonBody(new { grant_type = "client_credentials", client_id = clientIdParam, client_secret = appReg_clientSecret, ressource = _ressource }
);
var response = client.Post(request);
The problem is that the request's body is always null and the json body is added as a parameter
Any ideas?
https://login.microsoftonline.com/{{tenantId}}/oauth2/token
seems to not accept json, even with the content-type set as "application/json"
My solution:
var client = new RestClient("https://login.microsoftonline.com");
var request = new RestRequest("/{{tenantId}}/oauth2/token", Method.POST);
var requestBody = $"grant_type=client_credentials&client_id={clientIdParam}&client_secret={appReg_clientSecret}&resource={_resource}";
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", requestBody, ParameterType.RequestBody);
var response = client.Execute(request);

Creating a folder on box using C# and RESTSharp

I'm trying to use RESTSharp to create a simple folder on Box, but I'm having a hard time. I keep getting this error:
{"type":"error","status":400,"code":"bad_request","help_url":"http://developers.box.com/docs/#errors","message":"Could
not parse JSON","request_id":"1474540366505ba7a11bdcd"}
This is my code:
static string box(string resourceURL, string APIKey, string authToken)
{
RestClient client = new RestClient();
client.BaseUrl = "https://api.box.com/2.0";
var request = new RestRequest(Method.POST);
request.Resource = resourceURL;
string Headers = string.Format("Authorization: BoxAuth api_key={0}&auth_token={1}", APIKey, authToken);
request.AddHeader("Authorization", Headers);
request.AddParameter("name", "TestFolder");
// request.RequestFormat = DataFormat.Json;
var response = client.Execute(request);
return response.Content;
}
What am I missing? Thanks in advance for your help.
You may also want to take a look at a recently created github repo, where some folks are collaborating on a C# Box SDK. https://github.com/jhoerr/box-csharp-sdk-v2
I see two issues:
The URL needs to point to /folder/{folder_id} (0 is the id of the root folder)
The folder name needs to be in the json body of the request, not a query parameter
I'm not that familiar with C# or RESTSharp, but I believe this code should address the two problems.
static string box(string APIKey, string authToken)
{
RestClient client = new RestClient();
client.BaseUrl = "https://api.box.com/2.0";
var request = new RestRequest(Method.POST);
request.Resource = "/folders/0";
string Headers = string.Format("BoxAuth api_key={0}&auth_token={1}", APIKey, authToken);
request.AddHeader("Authorization", Headers);
request.AddParameter("text/json", "{\"name\" : \"TestFolderName\"}", ParameterType.RequestBody);
//request.RequestFormat = DataFormat.Json;
var response = client.Execute(request);
return response.Content;
}
Thanks for your help, this is the exact code that finally worked.
static string box(string APIKey, string authToken)
{
RestClient client = new RestClient();
client.BaseUrl = "https://api.box.com/2.0";
var request = new RestRequest(Method.POST);
request.Resource = "/folders/0";
string Headers = string.Format("BoxAuth api_key={0}&auth_token={1}", APIKey, authToken);
request.AddHeader("Authorization", Headers);
request.AddParameter("text/json", "{\"name\" : \"TestFolderName\"}", ParameterType.RequestBody);
//request.RequestFormat = DataFormat.Json;
var response = client.Execute(request);
return response.Content;
}
static string folderCreation(string APIKey, string authToken)
{
RestClient client = new RestClient();
client.BaseUrl = "https://api.box.com/2.0/folders";
var request = new RestRequest(Method.POST);
string Headers = string.Format("Bearer {0}", authToken);
request.AddHeader("Authorization", Headers);
request.AddParameter("application/json", "{\"name\":\"Youka\",\"parent\":{\"id\":\"0\"}}", ParameterType.RequestBody);
var response = client.Execute(request);
return response.Content;
}

Categories