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);
Related
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
Face API works with URL of the image but when I try to send image as
Base64 encoded it returns an error.
In this sample code I used Restsharp to send the data
My code is like below.
public string GenerateRest(String Base64Image)
{
var serviceURL = Constants.BaseServiceURI;
var client = new RestClient(serviceURL);
var request = new RestRequest(Constants.BaseResoruce, Method.POST);
request.AddHeader("Ocp-Apim-Subscription-Key", Constants.MS_API_KEY);
request.AddHeader("Content-Type", "application/octet-stream");
request.RequestFormat = DataFormat.Json;
var baseString = Base64Image.Replace("data:image/jpeg;base64,", String.Empty);
byte[] newBytes = Convert.FromBase64String(baseString);
request.AddBody(newBytes);
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
return content;
}
After fixing Restsharp request according to answer code is like
public FaceAPIOutput GenerateRest(String Base64Image)
{
var serviceURL = Constants.BaseServiceURI;
var client = new RestClient(serviceURL);
var baseString = Base64Image.Replace("data:image/jpeg;base64,", String.Empty);
byte[] newBytes = Convert.FromBase64String(baseString);
var request = new RestRequest(Constants.BaseResoruce, Method.POST);
request.AddHeader("Ocp-Apim-Subscription-Key", Constants.MS_API_KEY);
request.AddParameter("application/octet-stream", newBytes, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
return ConvertToFaceAPIOutObject(content);
}
Restsharp looks a bit idiosyncratic when taking a binary payload. Instead of request.AddBody, which adds a multipart form section, you need to do the following:
request.AddParameter("application/octet-stream", newBytes, ParameterType.RequestBody);
c.f. Can RestSharp send binary data without using a multipart content type?
I am trying to post a new customer to a web api. When I execute the following in Fiddler I get no errors:
POST https://api.someurl.com/api/businesses/99999999/contacts HTTP/1.1
User-Agent: Fiddler
Content-Type: application/json
Accept: application/json
Host: api.someurl.com
Authorization: TOKEN json:{"authenticationCode":"kLJBlaUCK0pYY6YXI6qB3CHamq0=","expiryDate":1468083160641,"locale":"en_US","myUserId":88888888888,"restriction":null,"site":"api.someurl.com"}
Content-Length: 931
{"business":9999999999,"collaborationContext":0,"contactInformation":{"campaign":null,"city":"SomeCity","country":"SomeCountry","email":"email#someurl.com","fax":null,"first":"FName","hasShippingAddress":false,"instructions":null,"last":"LName","locale":null,"mobile":null,"name":"FullName","phone":"222.333.4455","postalOrZipCode":"90210","provinceOrState":null,"readOnly":false,"referral":null,"registration":null,"shippingCity":null,"shippingCountry":null,"shippingName":null,"shippingNotes":null,"shippingPhone":null,"shippingPostalOrZipCode":null,"shippingProvinceOrState":null,"shippingStreet1":null,"shippingStreet2":null,"street1":null,"street2":null,"tollFree":null,"url":null},"currency":null,"defaultTaxCode":null,"id":0,"incomeOrExpenseAccount":null,"linkedBusiness":null,"payableAccount":null,"paymentAccount":null,"paymentTerms":null,"prefix":null,"receivableAccount":null,"removed":false,"type":"CUSTOMER"}
When I try to execute (what I think is) the equivalent (see below), I get "StatusCode: UnsupportedMediaType, Content-Type: text/xml, Content-Length: 0)"
private static string PostContact(string busId, Contact contact )
{
var restClient = new RestClient("https://api.someurl.com");
var jsonToken = GetJsonToken();
// var contactJson = JsonConvert.SerializeObject(contact);
var req = new RestRequest("/api/businesses/{business-id}/contacts");
req.Method = Method.POST;
req.Parameters.Clear();
req.AddHeader("Content-Type", "application/json");
req.AddHeader("Accept", "application/json");
req.AddUrlSegment("business-id", busId);
req.AddParameter("Authorization", string.Format("TOKEN json:{0}", jsonToken), ParameterType.HttpHeader);
req.AddParameter("application/json", contact, ParameterType.RequestBody);
var resp = restClient.Execute(req);
Console.WriteLine(resp.StatusCode);
return resp.Content;
}
Is there a special order to adding parameters or headers, or am I missing something?
Resolved!
var client = new RestClient(url);
var request = new RestRequest(Method.POST);
request.AddHeader("Cache-Control", "no-cache");
///request.AddHeader("Authorization", "Bearer " + access_token);
request.AddHeader("Authorization", token);
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("undefined", JsonRequest, ParameterType.RequestBody);
var response = client.Execute(request);
var responseJson = response.Content;
I have another easier solution:
Add this single line (if NO file is attached)
req.AlwaysMultipartFormData = true;
In my case a piece of source code look like this:
var client2 = new RestClient("https://myurl.com/api/site/Create");
client2.Options.MaxTimeout = -1;`
var request2 = new RestRequest("https://myurl.com/api/site/Create", Method.Post);
request2.AddHeader("Authorization", "Bearer "+ _authstr);
// AddFile below, therefore commented out
// request2.AlwaysMultipartFormData = true;
request2.AddParameter("PFolderId", "a1c1w000000GR5hAAG");
request2.AddParameter("Title", "MyTitle5");
request2.AddParameter("GeoRegion", "{E|BE|BRUXELLES-BRUSSEL}");
request2.AddParameter("SeismicZone", "0");
request2.AddFile("file", "C:/Users/abc/Desktop/Drawing.png");
RestResponse response2 = client.Execute(request2);
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));
}
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;
}