Creating a folder on box using C# and RESTSharp - c#

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;
}

Related

Returning result from RestClient.Content ('result' is a variable but is used like a type)

I'm new to c# and I'm trying to return the data I get from a restClient to use later in my Program.
public string SlackGet(string parameterJsonObject, string url, string token)
{
var client = new RestClient(url);
var request = new RestRequest(Method.GET);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", $"Bearer {token}");
request.AddParameter("application/json", parameterJsonObject, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var result =(response.Content);
Console.WriteLine(result);
return(result);
Console.WriteLine($"done!");
}
With this I am recieving the following error 'result' is a variable but is used like a type
What am I doing wrong?
TIA

Oauth 2.0 RestSharp passing accesstoken

Following on from my last question I have made some progress but still stuck
I am able to obtain the accessToken using this SetUp method in the test class
but when I try to run the test CanGetAllCountries it still says it is unauthorized
How can i pass the accessToken to authorize the second test?
public class APITestCustomer
{
public static string baseUrl = "https://www.example.net/umbraco/api/";
[SetUp]
public void OAuthLogonSetup()
{
var client = new RestClient(baseUrl);
RestRequest request = new RestRequest("UsersApi/Logon") { Method = Method.POST };
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-type", "application/x-www-form-urlencoded");
request.AddParameter("Username", "xxxxxx");
request.AddParameter("Password", "xxxxxx");
request.AddParameter("grant_type", "client_credentials");
var response = client.Execute(request);
var responseJson = response.Content;
var token = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseJson)["accessToken"].ToString();
//Assert.That(token.Contains("test"));
}
[Test]
public void CanGetAllCountries()
{
RestClient client = new RestClient(baseUrl);
RestRequest request = new RestRequest("CountryApi/GetAll", Method.GET);
request.AddHeader("Authorization", "Bearer");
IRestResponse response = client.Execute(request);
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
}
}
}
For reaching this you could use the following modifications on your code:
public class APITestCustomer
{
public static string baseUrl = "https://www.example.net/umbraco/api/";
private string token;
[SetUp]
public void OAuthLogonSetup()
{
var client = new RestClient(baseUrl);
RestRequest request = new RestRequest("UsersApi/Logon") { Method = Method.POST };
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-type", "application/x-www-form-urlencoded");
request.AddParameter("Username", "xxxxxx");
request.AddParameter("Password", "xxxxxx");
request.AddParameter("grant_type", "client_credentials");
var response = client.Execute(request);
var responseJson = response.Content;
token = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseJson)["accessToken"].ToString();
//Assert.That(token.Contains("test"));
}
[Test]
public void CanGetAllCountries()
{
RestClient client = new RestClient(baseUrl);
RestRequest request = new RestRequest("CountryApi/GetAll", Method.GET);
request.AddHeader("Authorization", $"Bearer {token}");
IRestResponse response = client.Execute(request);
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
}
}
}

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

RestSharp C# HTTP POST Oauth 1

I am running into a difficulty with HTTP POST and Oauth 1, RestClient C#. I am able to make successful calls with HTTP GET and Oauth, but for some reason HTTP Post fails. I was able to make successful HTTP POST calls with same credentials using Postman, but not with RestSharp. Perhaps someone could help me figuring out the issue.
Here are the screenshots with working HTTP POST Oauth1 Postman call:
The Postman setup above works just fine, and here is what I have so far in C# and RestClient:
public bool CreateShippingTemplate(string storeProviderStoreId, string consumerKey, string consumerSecret, string oAuthToken, string oAuthTokenSecret)
{
string url = "/shipping/templates";
var request = GenerateSecureRequest(url, RequestType.POST, consumerKey, consumerSecret, oAuthToken, oAuthTokenSecret);
var dataObj = new //ShippingTemplate
{
title = "Test Title 2",
origin_country_id = "209",
primary_cost = "1",
secondary_cost = "1"
};
string dataObjJson = JsonConvert.SerializeObject(dataObj);
request.AddParameter("application/json", dataObjJson, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;
request.Method = Method.POST;
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
var response = _restClient.ExecuteAsPost(request,"POST");
return true;
}
private RestRequest GenerateSecureRequest(string url, RequestType requestType, string consumerKey, string consumerSecret, string oAuthToken, string oAuthTokenSecret)
{
OAuthBase oAuth = new OAuthBase();
string nonce = oAuth.GenerateNonce();
string timeStamp = oAuth.GenerateTimeStamp();
string normalizedUrl;
string normalizedRequestParameters;
string relativeUri = url;
string sig = oAuth.GenerateSignature(new Uri(BASE_URL.ToString() + relativeUri), consumerKey, consumerSecret, oAuthToken, oAuthTokenSecret, requestType.ToString(), timeStamp, nonce, out normalizedUrl, out normalizedRequestParameters);
var request = new RestRequest(relativeUri);
request.Resource = string.Format(relativeUri);
request.Method = Method.GET;
request.AddParameter("oauth_consumer_key", consumerKey);
request.AddParameter("oauth_token", oAuthToken);
request.AddParameter("oauth_nonce", nonce);
request.AddParameter("oauth_timestamp", timeStamp);
request.AddParameter("oauth_signature_method", "HMAC-SHA1");
request.AddParameter("oauth_version", "1.0");
request.AddParameter("oauth_signature", sig);
return request;
}
I tried many things with RestClient and C#, nothing worked. What am I missing, in order to match the working Postman request. HTTP GET is working for me in RestSharp, only HTTP Post is not working.
Thank you
Ok, I finally got my working, went the same wrong way trying to implement signature creation myself.. as I badly interpreted PostMan RestSharp code.
This could be done much easier as RestSharp does it all for you! I wish this was the version PostMan gave as a "code" example. Anyway, this works for me in C# (quick console app):
const string consumer_key = "abcd1234";
const string consumer_secret = "1234abcd";
const string access_token = "1a2b3c4d";
const string token_secret = "a12b3c4d";
const string URL = "https://aa.web.site.net/history/api/account/123456789/givemedata/search?offset=0&limit=50";
static void Main(string[] args)
{
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
var client = new RestClient(URL);
client.Authenticator = OAuth1Authenticator.ForAccessToken(consumer_key, consumer_secret, access_token, token_secret, RestSharp.Authenticators.OAuth.OAuthSignatureMethod.HmacSha1);
client.Timeout = -1;
var request = new RestRequest(URL, Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\"start\": {\"from\": 1583074556000, \"to\": 1588258556000 } }", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Console.ReadKey();
}
Yes, I know, no headers, no param sorting and hashing.. no nonce-nse :)
thanks Pete, this code saves me hours of try and error!
the only code I added here is Realm
OAuth1Authenticator lAuthenticator = OAuth1Authenticator.ForAccessToken(consumer_key, consumer_secret, access_token, token_secret, RestSharp.Authenticators.OAuth.OAuthSignatureMethod.HmacSha256);
lAuthenticator.Realm = "my_Realm";
client.Authenticator = lAuthenticator;

Converting HttpClient to RestSharp

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

Categories