How to add both parameter and file image to the body request - c#

I have weird question, I can't add both parameter specially aliasId and file Image in same Debug configuration
If I remove line request.AddHeader("Content-Type", "multipart/form-data; boundary=<calculated when request is sent>"); if I keep it I can't add the Parameter, other way if I remove it I can add Image but wrong type.
public static string Register(/*GuestData guestData*/)
{
string urlImage = "D:\\CLOUDX\\EyeQTech\\faceid\\itsme.jpg";
RestClient client = new RestClient("api/domain/faceid/");
var request = new RestRequest("register", Method.Post);
request.AddHeader("Authorization", token);
request.AddHeader("Cookie", "__cflb=02DiuDSnUsPgiMQzVNimjJdcPn2DXK4ZqAx6U3Qmmk1QQ");
request.AddHeader("Content-Type", "multipart/form-data; boundary=<calculated when request is sent>"); //add content type is here
request.RequestFormat = DataFormat.Json;
request.AddFile(name: "images[]", path: urlImage); // add file to body
request.AddBody(new Dictionary<string, string>()
{{"organization", "internal-dev"},
{"aliasId", "900"}
}); //add body parameter
RestResponse response = client.Execute(request);
MessageBox.Show(response.Content);
Console.WriteLine(response.Content);
return response.Content;
}

Related

Why restsharp don't get Parameter?

I code C#. In my C# code add parameter "aliasID" and send request without "aliasID".
But when I use Postman, I add "aliasID" and it was sent.
Code
namespace TrainEyeQTech.ViewModel
{
internal static class SetupAPI
{
public static void Register()
{
RestClient client = new RestClient("faceid/api/domain/register");
//client.Timeout = -1;
var request = new RestRequest("", Method.Post);
request.AddHeader("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiaW50ZXJuYWwtcmVnaXN0ZXIiLCJzZXJ2aWNlIjoiZmFjZWlkLXJlZ2lzdGVyIiwiZXh0cmEiOiJpbnRlcm5hbC1kZXYiLCJpYXQiOjE2MzUwODgzMjAsImV4cCI6MTY2NjYyNDMyMH0.8CBqXQNuCYXBjK7Nt4_fw1rZPIgK6WdZRbhIvWyaS1s");
request.AddHeader("Content-Type", "multipart/form-data; boundary=<calculated when request is sent>");
request.AddHeader("Cookie", "__cflb=02DiuDSnUsPgiMQzVNimjJdcPn2DXK4ZqAx6U3Qmmk1QQ");
request.AddHeader("Content-Length", "<calculated when request is sent>");
request.AddHeader("Connection", "keep-alive");
//request.AddHeader("Host", "<calculated when request is sent>"); here will be error
request.AddHeader("User-Agent", "PostmanRuntime/7.29.2");
request.AddHeader("Accept-Encoding", "gzip, deflate, br");
request.AddHeader("Postman-Token", "<calculated when request is sent>");
request.AddParameter("organization", "internal-dev");
request.AddFile("images[]", "D:\\CLOUDX\\EyeQTech\\faceid\\itsme.jpg");
request.AddParameter("aliasId", "123_cuong"); // here don't add aliasId prameter
RestResponse response = client.Execute(request);
Console.WriteLine(response.Content); //{messenge: missing aliasID}
}
}
Postman
enter image description here
Here is headers of Postman
enter image description here

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

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

Face API Base64 image post returns badrequest

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?

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